Outline

Exercise Goal

Create an Angular Structural Directive to insert an element and immediately hide the element.

Tasks

  1. Open the if-and-hide.directive.ts file located in the src/app/directives directory.
  2. Define a new setter method for the appIfAndHide property within the IfAndHideDirective class. When the value of the property is set, this function will be invoked with a boolean condition value specified as the first, and only, argument.
  3. Apply the @Input() decorator to the setter method you just created for the appIfAndHide property.
  4. Within the setter method, invoke the create() method if the value of the condition argument is true, else, invoke the remove() method.
  5. Next, we need to inject a few classes via the constructor() function that our directive requires, namely: Renderer2, TemplateRef, and ViewContainerRef.
  6. Within the create() method invoke the createEmbeddedView() method on the injected ViewContainerRef class instance, providing the TemplateRef instance. Iterate over the rootNodes property of the embedded view, and for each node, set the display CSS style to the value none.
  7. Then, within the remove() method invoke the clear() method on the ViewContainerRef class instance in order to destroy all views in the container.
  8. Finally, test your solution using the Developer Tools inspection to note that the <div> element is created, but the display style is set to none when the value of the loading boolean property in the AppComponent class is set to true.

Exercise

Exercise Problem

Notes

  • Be sure to use the Inspect developer tools within the browser to monitor the result of the <div> in the app.component.html template on which the NgIfAndHide structural directive is applied.
  • The Renderer2, TemplateRef, and ViewContainerRef class instances are already imported at the top of the if-and-hide.directive.ts file, but don't forget to inject them via dependency injection in the IfAndHideDirective class's constructor() function.
  • You may want to refer to the https://angular.io/api/core/ViewContainerRef#viewcontainerref documentation for the behavior of both the createEmbeddedView() and clear() methods.
 

I finished! On to the next chapter