Reactive Cycles in Angular
Reactivity will also work in the ngFor
loop. This means that when the array changes, these changes will be immediately reflected on the screen.
Let's try it in practice. Let's say we have the following array:
export class AppComponent {
public arr: string[] = ['a', 'b', 'c', 'd'];
}
Let's output our array in a loop as a list:
<ul>
<li *ngFor="let elem of arr">
{{ elem }}
</li>
</ul>
Let's make a button that, when clicked, will call the class method:
<button (click)="add()">
add
</button>
In this method, we will somehow change our array, for example, add a new element to it:
export class AppComponent {
public text: string = '';
public add(): void {
this.arr.push('!');
}
}
Now, if you run the code and click the button, a new element will appear in the list immediately after clicking.
Given an array. Output its elements in a loop. Make a button that, when pressed, will delete the last element from the array.