Creating and using a structural directive in Angular 13

Tram Ho

Structural directives change the DOM layout by adding and removing DOM elements.
DOM in Javascript stands for Document Object Model , roughly translated as the model of objects in HTML documents.
Through the DOM model, we can access HTML tags easily. (You can learn more about the DOM online).
Angular has provided a set of built-in structural directives (such as NgIf , NgForOf , NgSwitch and others) that are commonly used in all Angular projects.
When structural directives are applied, they are usually prefixed with an asterisk, * , such as *ngIf.

Creating a structural directive

In this section we will create an UnlessDirective , this directive is responsible for showing or hiding a piece of text based on the value of the condition property in the AppComponent .
UnlessDirective does the opposite of NgIf and the values ​​of the condition attribute can be set to true or false . UnlessDirective will display content when condition is false .

  1. First we use the command below to create a structural directive named unless

2.Continue to import Input , TemplateRef , and ViewContainerRef .
src/app/unless.directive.ts

3.Insert TemplateRef and ViewContainerRef in directive constructor as private variables.
src/app/unless.directive.ts

TemplateRef helps you to access <ng-template> content and ViewContainerRef accesses the view container.

4. Add the appUnless @Input () property with a setter.
src/app/unless.directive.ts

Angular sets the appUnless property whenever the value of the condition changes.
– If condition is false and Angular has not created the view before, the viewContainer setter will create the embedded view(createEmbeddedView ) from the template
– If condition is true and the view is currently displayed, the setter will clear the container, discarding the view

Update the full code as follows:
src/app/unless.directive.ts

Testing the directive

1.Update code file src/app/app.component.ts
Add a condition set to false in AppComponent.

2. Update template to use directive. Here, appUnless is on top of two <p> tags with opposing condition values, one true and one false .
src/app/app.component.html

The * in front of appUnless to represent appUnless as a structural directive
When the condition is false, the top fragment (A) appears and the bottom fragment (B) disappears.
When the condition is true, the top fragment (A) disappears and the bottom fragment (B) appears.

That’s the end of the post, hope the article is useful to you!

Share the news now

Source : Viblo