HDTuto.com

Angular Push Object into Array Example



In this article we will cover on how to implement angular push element in array. I’m going to show you about angular push object into array. if you have question about angular object push key value then i will give simple example with solution. you will learn push object in array in angular. You just need to some step to done how to add element in array angular.

we will use push and unshift function of array so we can add key value in array. you can easily add add value on top using unshift in array.

So, let's see bellow example that will help you how you can add object and item into array. i also give you simple and with object example.

Example 1:

src/app/app.component.html

<button (click)="addNew()">Add</button>

src/app/app.component.ts

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

myArray = [1, 2, 3, 4, 5, 6];

addNew(){

this.myArray.push(this.myArray.length + 1);

console.log(this.myArray);

}

}

Output:

[1, 2, 3, 4, 5, 6, 7]

[1, 2, 3, 4, 5, 6, 7, 8]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Example 2:

src/app/app.component.html

<button (click)="addNew()">Add</button>

src/app/app.component.ts

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

myObjArray = [

{id: 1, name: "Hardik" },

{id: 2, name: "Vimal" },

{id: 3, name: "Paresh" }

];

addNew(){

this.myObjArray.push({id: 4, name: "Vimal"});

console.log(this.myObjArray);

}

}

Output:

[Object, Object, Object, Object, Object]

0: Object

1: Object

2: Object

3: Object

4: Object

id: 4

name: "Vimal"

__proto__: Object

Example 3: Add on Top

src/app/app.component.html

<button (click)="addNew()">Add</button>

src/app/app.component.ts

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

myObjArray = [

{id: 1, name: "Hardik" },

{id: 2, name: "Vimal" },

{id: 3, name: "Paresh" }

];

addNew(){

this.myObjArray.unshift({id: 4, name: "Vimal"});

console.log(this.myObjArray);

}

}

Output:

[Object, Object, Object, Object, Object]

0: Object

id: 4

name: "Vimal"

__proto__: Object

1: Object

2: Object

3: Object

I hope it can help you...




April 26, 2020 | Category : Angular



Blog Search