Blog>
Snippets

Displaying Conditional Content with ngIf

Use ngIf to conditionally include an element in the DOM. This example toggles a paragraph element based on a component's boolean property.
import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `
    <h1>Welcome to my App!</h1>
    <p *ngIf="showParagraph">This paragraph is conditionally rendered.</p>
    <button (click)="toggleParagraphVisibility()">Toggle Paragraph</button>
  `
})
export class MyComponent {
  showParagraph: boolean = true;

  toggleParagraphVisibility(): void {
    this.showParagraph = !this.showParagraph;
  }
}
This JavaScript code is a component using Angular's ngIf structural directive to conditionally render a paragraph in the DOM. The 'showParagraph' property determines the presence of the paragraph. The 'toggleParagraphVisibility' method toggles this property when the button is clicked, thus showing or hiding the paragraph.