Add new list without refreshing the list in angular
In Angular, you can add a new item to a list without refreshing the list by using the push()
method to add the new item to the existing array, and then updating the list in the template using the ngFor
directive.
Here is an example:
// component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
<button (click)="addItem()">Add Item</button>
`
})
export class ExampleComponent {
items = ['Item 1', 'Item 2'];
addItem() {
this.items.push('New Item');
}
}
In this example, the items
array is initialized with two items, and the addItem()
method is called when the "Add Item" button is clicked. The addItem()
method uses the push()
method to add a new item to the items
array.
The ngFor
directive is used in the template to iterate over the items
array and display each item in a list. When the addItem()
method is called, the ngFor
directive will automatically update the list to include the new item without refreshing the page.
You can also use splice()
method to add item at specific position
addItem() {
this.items.splice(0, 0, 'New Item');
}
This will add the new item at the beginning of the array.
You can also use Observable
and Subject
to push new item to the list without refreshing the page.
// component.ts
import { Component } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'app-example',
template: `
<ul>
<li *ngFor="let item of items | async">{{ item }}</li>
</ul>
<button (click)="addItem()">Add Item</button>
`
})
export class ExampleComponent {
items = new Subject<any>();
addItem() {
this.items.next(['New Item']);
}
}
In this example, we use Subject
to create an observable that emits the new item. We then use the async
pipe in the template to subscribe to the observable and display the items.
You can also use push()
method with ChangeDetectorRef
to update the list without refreshing the page.
// component.ts
import { Component } from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
<button (click)="addItem()">Add Item</button>
`
})
export class ExampleComponent {
items = ['Item 1', 'Item 2'];
cdRef: ChangeDetectorRef;
constructor(cdRef: ChangeDetectorRef) {
this.cdRef = cdRef;
}
addItem() {
this.items.push('New Item');
this.cdRef.detectChanges();
}
}
In this example, we use ChangeDetectorRef
to detect changes to the items
array and update the list without refreshing the page.