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
<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');
}
}
How can I do this?
You are using an array widgets
and can use the push method to add an element at the end of array. To maintain dynamic id
and name
we can use the length
property of Array's like below:
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 } })
}
You can do this:
addWidget() {
this.widgets.push({ id: 3, title: 'Widget 3', config: { row: 1, col: this.widget.length, sizex: 1 }})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.