Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ngIf without an extra element in Angular 2

Can I use ngIf without an extra container element?

<tr *ngFor="...">
  <div *ngIf="...">
    ...
  </div>
  <div *ngIf="!...">
    ...
  </div>
</tr>

It doesn't work in a table because that would make invalid HTML.

like image 369
janispritzkau Avatar asked Oct 18 '22 20:10

janispritzkau


People also ask

Does ngIf destroy component?

Angular's ngIf directive does not simply hide and show. It creates and destroys an HTML element based on the result of a JavaScript expression.

Does ngIf remove element from DOM?

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

How do you use ngIf with multiple conditions?

We can use multiple conditions in *ngIf with logical operator AND (&&) to decide the trustworthy of *ngIf expression. If all conditions are true, then element will be added to the DOM.

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.


1 Answers

ng-container is preferred over template:

<ng-container *ngIf="expression">

See:

Angular 2 ng-container

https://github.com/angular/angular.io/issues/2303

like image 227
Alexander Taylor Avatar answered Oct 20 '22 10:10

Alexander Taylor