Directives are classes that add additional behavior to elements in your Angular applications. Use Angular’s built-in directives to manage forms, lists, styles, and what users see. We use directives to manipulate the DOM.
NgFor
Loop through the list items and output them with ngFor.
<app-server *ngFor="let server of servers"></app-server>
Add index to list items
<div *ngFor="let item of items; let i = index">
<h3>{{i + 1}}. {{item}}</h3>
Loop ngFor specific number of times
Method #1
*ngFor="let e of [].constructor(3)
Method #2
Another way to *ngFor loop defined number of times
TS
//function to return list of numbers from 0 to n-1
numSequence(n: number): Array<number> {
return Array(n);
}
HTML
*ngFor="let n of numSequence(3)"
NgIf
A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause. The default template for the else clause is blank.
<p *ngIf="serverCreated">Server was created, server name is {{serverName}}</p>
<ng-template>
We mark a certain spot in the template which we want to show conditionally. With <ng-template>, you can define template content that is only being rendered by Angular when you, whether directly or indirectly, specifically instruct it to do so, allowing you to have full control over how and when the content is displayed.
<ng-template #noServer>No Server was created!</ng-template>
<p *ngIf="serverCreated; else noServer">Server was created, server name is {{serverName}}</p>
<ng-container>
The <ng-container> allows us to use structural directives without any extra element, making sure that the only DOM changes being applied are those dictated by the directives themselves.
One common use case of <ng-container> is alongside the *ngIf structural directive. By using the special element we can produce very clean templates easy to understand and work with.
<ng-container *ngIf="condition"> … </ng-container>
Combination of multiple structural directives
Multiple structural directives cannot be used on the same element; if you need to take advantage of more than one structural directive, it is advised to use an <ng-container> per structural directive.
This would not work
Because we can’t have more than one structural directive on the same element:
<ul>
<li *ngFor="let item of items" *ngIf="item.isValid">
{{ item.name }}
</li>
</ul>
What we can do is to simply move one of the structural directives to an <ng-container> element, which would then wrap the other one, like so:
<ul>
<ng-container *ngFor="let item of items">
<li *ngIf="item.isValid">
{{ item.name }}
</li>
</ng-container>
</ul>