Reputation: 45
here is the sample code for the asked question.<p *ngIf="heroes.length >= 4">There are many heroes!</p>
If i remove * it gives me error
Upvotes: 3
Views: 2739
Reputation: 41
The reason we use asterik for ngIf and ngFor directive is because, they change the structure of the DOM. and they are also called as structural directives. Every structural directive prefix with asterik.
Examples of Structural directives: *ngIf, *ngFor, *ngSwitchCase, *ngSwitchDefault etc are some examples of structural directives
Code Example:
<p *ngIf="true"> Expression is true and ngIf is true. This paragraph is in the DOM. </p>
<p *ngIf="false"> Expression is false and ngIf is false. This paragraph is not in the DOM.</p>
checkout this link to dive deep in structural directives: https://angular.io/guide/structural-directives
Upvotes: 3
Reputation: 349
source:https://angular.io/docs/ts/latest/guide/structural-directives.html#!#asterisk
The asterisk (*) effect
COPY CODE
<div *ngIf="hero">{{hero}}</div>
<div *ngFor="let hero of heroes">{{hero}}</div>
We're prefixing these directive names with an asterisk (*).
The asterisk is "syntactic sugar". It simplifies ngIf and ngFor for both the writer and the reader. Under the hood, Angular replaces the asterisk version with a more verbose form.
The next two ngIf examples are effectively the same and we may write in either style:
COPY CODE
<!-- Examples (A) and (B) are the same -->
<!-- (A) *ngIf paragraph -->
<p *ngIf="condition">
Our heroes are true!
</p>
<!-- (B) [ngIf] with template -->
<template [ngIf]="condition">
<p>
Our heroes are true!
</p>
</template>
Most of us would rather write in style (A).
It's worth knowing that Angular expands style (A) into style (B). It moves the paragraph and its contents inside a tag. It moves the directive up to the tag where it becomes a property binding, surrounded in square brackets. The boolean value of the host component's condition property determines whether the templated content is displayed or not.
Upvotes: 6