Angular
Fundamentals of Angular Directives - Structural Directives

NgIf Structural Directive Exercise

PRO

Learn to use the NgIf structural directive in Angular

Exercise Goal

Insert and remove elements based on the happy property value.

Tasks

  1. Open app.component.html
  2. Using the NgIf structural directive, toggle the redendering of the <span> elements that inculde emojis on lines 2 and 3 based on the value of the happy property that is defined in the AppComponent class.
  3. Again, using the NgIf structural directive, toggle the rendering of the <span> elements that include the text "Happy" and "Sad" on lines 8 and 9 to appropriately render the element based on the value of the happy property that is defined in the AppComponent class.

Exercise

Exercise Problem

Notes

  • The value of happy is set to true by default in the AppComponent class.
  • We toggle the value of happy via the click event that occurs when the user clicks/taps on the <button>.
  • Go ahead and use the inspect developer tool to note that the <span> elements are not just displayed or hidden, rather, the elements are either injected or removed from the DOM during runtime.