Javascript Angular 5 - 将新元素推入数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47866361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 5 - Push new element into array
提问by Dhyey
I have a function on a button click which I want it to add a new line to the current widgets data so that it will add a new one to the current.
我有一个按钮单击功能,我希望它向当前小部件数据添加一个新行,以便它将新添加到当前小部件数据中。
Here is the code:
这是代码:
app.component.html
应用程序组件.html
<a (click)="addWidget()" class="btn btn-primary pull-right navbar-btn">Add Widget</a>
app.component.ts
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
public widgets: any;
constructor() {
let count = 1;
this.widgets = [
{ id: 1, title: 'Widget 1', config: { row: 1, col: 1, sizex: 1 }},
{ id: 2, title: 'Widget 2', config: { row: 1, col: 2, sizex: 1 } },
];
this.widgets.map(() => {
count++;
});
}
addWidget() {
console.log('This will add a new widget');
}
}
How can I do this?
我怎样才能做到这一点?
回答by Dhyey
You are using an array widgetsand can use the
pushmethod to add an element at the end of array. To maintain dynamic idand namewe can use the lengthproperty of Array's like below:
您正在使用数组,widgets并且可以使用
push方法在数组末尾添加一个元素。为了保持动态id,name我们可以使用lengthArray 的属性,如下所示:
addWidget() {
const title: string = 'Widget ' + this.widgets.length;
this.widgets.push({ id: this.widgets.length + 1, title: title, config: { row: 1, col: 3, sizex: 1 } })
}
回答by Amal
You can do this:
你可以这样做:
addWidget() {
this.widgets.push({ id: 3, title: 'Widget 3', config: { row: 1, col: this.widget.length, sizex: 1 }})
}

