Create an Angular Structural Directive to insert an element and immediately hide the element.
- Open the if-and-hide.directive.ts file located in the src/app/directives directory.
- Define a new setter method for the
appIfAndHideproperty within the
IfAndHideDirectiveclass. When the value of the property is set, this function will be invoked with a boolean
conditionvalue specified as the first, and only, argument.
- Apply the
@Input()decorator to the setter method you just created for the
- Within the setter method, invoke the
create()method if the value of the
true, else, invoke the
- Next, we need to inject a few classes via the
constructor()function that our directive requires, namely:
- Within the
create()method invoke the
createEmbeddedView()method on the injected
ViewContainerRefclass instance, providing the
TemplateRefinstance. Iterate over the
rootNodesproperty of the embedded view, and for each node, set the
displayCSS style to the value
- Then, within the
remove()method invoke the
clear()method on the
ViewContainerRefclass instance in order to destroy all views in the container.
- Finally, test your solution using the Developer Tools inspection to note that the
<div>element is created, but the
displaystyle is set to
nonewhen the value of the
loadingboolean property in the
AppComponentclass is set to
- 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
NgIfAndHidestructural directive is applied.
ViewContainerRefclass 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
- You may want to refer to the https://angular.io/api/core/ViewContainerRef#viewcontainerref documentation for the behavior of both the