📜  ng if else - Html (1)

📅  最后修改于: 2023-12-03 15:03:10.445000             🧑  作者: Mango

ng if else - Html

Ng if else is a structural directive in Angular, which is used to display content based on a condition. If the condition is true, it displays one set of content; otherwise, it displays another.

Syntax

The syntax for the ngIf Else statement is as follows:

*ngIf = "condition; else elseBlock"

In this statement, "condition" is the expression that evaluates to true or false. If it is true, the content specified before the "else" would be displayed. If it is false, the content specified after "else" would be displayed.

Example

The following example demonstrates the use of ngIf Else in a component:

<ng-container *ngIf="condition; else elseBlock">
  <div>Content to display if condition is true.</div>
</ng-container>

<ng-template #elseBlock>
  <div>Content to display if condition is false.</div>
</ng-template>

In this example, if the condition is true, the content inside the ng-container element would be displayed. If it is false, the content inside the ng-template element would be displayed.

Note
  • The ng-template element is used to define a template that can be used to render different parts of the component.
  • The ng-container element is used to group elements without creating an additional element in the DOM.
Conclusion

In conclusion, ngIf Else is a powerful directive that can be used to display content based on a condition in Angular. It provides a simple and efficient way to control the rendering of HTML elements in a component.