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:
appponent.html
<a (click)="addWidget()" class="btn btn-primary pull-right navbar-btn">Add Widget</a>
appponent.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './appponent.html',
styleUrls: ['./appponent.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?
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?
Share Improve this question edited Dec 18, 2017 at 11:07 asked Dec 18, 2017 at 10:23 user8398743user8398743 7 | Show 2 more comments2 Answers
Reset to default 10You 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 }})
}
this.widgets.push({ id: 3, title: 'Widget 3', config: { row: 1, col: 3, sizex: 1 }})
toaddWidget()
? – erikvimz Commented Dec 18, 2017 at 10:24.map()
function? To get amount of entries inside of an array just use the.length
property. – erikvimz Commented Dec 18, 2017 at 10:27any
. Try creating a class or interface for widget and config. – Nico Van Belle Commented Dec 18, 2017 at 10:27