gpt4 book ai didi

javascript - Angular 5 - 将新元素插入数组

转载 作者:行者123 更新时间:2023-12-01 15:51:42 25 4
gpt4 key购买 nike

我有一个按钮单击功能,我希望它向当前小部件数据添加一个新行,以便它将新添加到当前小部件数据中。

这是代码:

应用程序组件.html

 <a (click)="addWidget()" class="btn btn-primary pull-right navbar-btn">Add Widget</a>

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');
}

}

我怎样才能做到这一点?

最佳答案

您正在使用数组 widgets并且可以使用
push
在数组末尾添加元素的方法。保持动态idname我们可以使用 length Array 的属性如下所示:

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 } })
}

关于javascript - Angular 5 - 将新元素插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47866361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com