Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular why asterisk (*)

In Angular document, * and template, we know that the *ngIf, *ngSwitch, *ngFor can be expanded to ng-template tag. My question is:

I think the ngIf or ngFor without * can also be translated and expanded to template tag by Angular engine.

The following code

<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail> 

would be the same as

<ng-template [ngIf]="currentHero">   <hero-detail [hero]="currentHero"></hero-detail> </ng-template> 

So why bother designing a strange symbol asterisk(*) in Angular?

like image 744
maxisacoder Avatar asked Oct 17 '16 03:10

maxisacoder


People also ask

Why We Use * In structural directive in Angular?

It is used to hide or display the things on the DOM. Structural Directives can be easily identified using the '*'. Every Structural Directive is preceded by a '*' symbol.

What is use of * in Angular?

It's called Safe Navigation Operator which can be used to prevent Angular from throwing errors, when trying to access object properties of an object that don't exist. Here it is, protecting against a view render failure if the header is null.

What is the use of * in ngIf?

Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element. The *ngIf directive is most commonly used to conditionally show an inline template, as seen in the following example. The default else template is blank.

What is asterisk in ngFor?

In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag. Follow this answer to receive notifications.


1 Answers

Asterisk syntax is a syntatic sugar for more wordy template syntax which directive expands to under the hood, you are free to use any of these options.

Quote from the docs:

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:

<!-- 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> 
like image 51
Klaster_1 Avatar answered Sep 21 '22 19:09

Klaster_1