Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  88] [ 5]  / answers: 1 / hits: 48944  / 7 Years ago, mon, december 18, 2017, 12:00:00

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?


More From » angular

 Answers
8

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

[#55655] Thursday, December 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;