You can use the *ngIf
directive in combination with the else
clause to conditionally render different content based on a condition in Angular templates. Here's an example:
html<div *ngIf="showContent; else elseBlock">
<!-- Content to display when the condition is true -->
<p>This content is displayed when showContent is true.</p>
</div>
<ng-template #elseBlock>
<!-- Content to display when the condition is false -->
<p>This content is displayed when showContent is false.</p>
</ng-template>
In the example above, the *ngIf
directive checks the value of the showContent
property. If it evaluates to true
, the content within the div
element is displayed. Otherwise, the content within the elseBlock
template is rendered.
Make sure that you have a corresponding property showContent
defined in your component class. It can be a boolean property that determines whether to show or hide the content:
typescriptimport { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
showContent: boolean = true;
}
You can update the value of showContent
based on your application logic or user interactions. When the value changes, the template will automatically re-evaluate the *ngIf
condition and render the appropriate content.
Using *ngIf
with else
allows you to create conditional rendering in Angular templates, giving you flexibility to display different content based on specific conditions.
Comments
Post a Comment