Issue
I am trying to add data to an object with a button click but nothing is happening.
Here is the code:
HTML:
{{ data | json }}
<button (click)="add()">Add Data</button>
TS:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
newData: any[] = [];
data = [
{
id: 1,
name: 'cars',
data: [
{ description: 'Honda' },
{ description: 'Mini' },
{ description: 'Vaux' }
]
},
{
id: 2,
name: 'bands',
data: [
{ description: 'Band 1' },
{ description: 'Band 2' }
]
},
{
id: 3,
name: 'animals',
data: [
{ description: 'Dog' },
{ description: 'Cat' }
]
},
{
id: 4,
name: 'names',
data: this.newData // DATA NEEDS TO BE ADDED HERE
}
]
add() {
this.newData = [
{ description: 'Tom' },
{ description: 'Paul' },
{ description: 'Frank' }
]
}
}
Nothing happens when I click add(). I've also checked the console for any issues there and there are not issue reported in the console.
How can I fix this?
Solution
In your 'add' method you need to assign the new data
add(){
this.newData = [
{ description: 'Tom' },
{ description: 'Paul' },
{ description: 'Frank' }
];
//add the `newData` to the 3 element of the `data` array
this.data[3].data = this.newData;
}
Answered By - martin66
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.