*ngFor with Change Detection
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
cars = [
{ id: 1, name: 'rav4' },
{ id: 2, name: 'crv' },
{ id: 3, name: 'rx8' },
]
onAdd() {
this.cars.push({ id: 4, name: 'civic' });
}
onRemove(car) {
let index = this.cars.indexOf(car);
this.cars.splice(index, 1);
}
}
<!--
ngFor
* Also getting the value of index
* For more information visit... https://angular.io/api/common/NgForOf
-->
<button class="btn" (click)="onAdd()">Add</button>
<ul class="collection">
<li *ngFor="let car of cars" class="collection-item">
{{ car.name }}
<button (click)="onRemove(car)" class="btn red">Remove</button>
</li>
</ul>