Learn the basics of Directives in Angular

Tram Ho

1 What is Directives?

Directives is an object that makes it easy to modify another object and the application is very simple and flexible. Directives can be understood as the typescript (or javascript) code with HTML and when called, it is called as HTML. For example:

2. Classification of directives

From Angular 2 onwards, directives are divided into the following categories:

  1. Components directives : There’s no doubt calling a component a directive, since it’s obvious that the component allows to define a selector and call it as an html tag ( <component-name> </component-name> )
  2. Structural directives : Structural directives are used to draw html, display data on an html interface, and change the DOM structure by adding or removing elements in the DOM. Structural directives often have an ‘ * ‘ in front of the directive. For example * ngFor , * ngIf
  3. Attribute directives : Change the look, interaction of objects or change other directives or add dynamic attributes to html element. for example * ngStyle

3. Components directives

Components directives are used very commonly, you can see Components directives here. Here, I will briefly describe this directives.

Components is a block of code in an Angular app. It is a combination of html template set (html framework) and embedded TypeScript (or Javascript) code. The components are independent of each other and independent of the system. It can be easily inserted or removed from the system. A component can be understood as a control on the display screen, including the html interface and the event handling logic associated with that control. A component can be as large as an entire monitor containing multiple controls or a group of monitors. That is, a component can also contain and call many other components connected. Thus, Angular is very flexible in breaking down code into components.

In Angular we declare a Component with the following structure:

As we can see the Component keyword helps define a html framework for it. And below is a class HelloWorld used to write logic code. In the html framework definition, we have the following properties to note:

  • selector : The name given to call a component in html code. In the example just now, the keyword app-hello-world is named for this component. When we need to call this component in the parent html screen, we will call it with html tag <app-hello-world> </app-hello-world> . Calling so, the child component will be rendered to the parent component.
  • template : Is a self-defined html frame for string-type components in this file. The example above just defines a simple html h1 tag. This method is for simple components only.
  • templateUrl : Is the url to an external html file to load that file as the html frame for this component. This is a common way of coding because it allows separating the html frame from the logic code, the designer will edit the html file separately, independently of the coder.
  • styles : is to write style css always into this component file. This method is for simple components only.
  • styleUrls : The url to the independent style css file for this component. This way is recommended because the css file should be reserved for the designer to touch.

4. Structural directives

In the following, I will present some basic and common structural directives. Also you can refer and see details here Stuctural directives

4.1 Ng-if… else

Effect of checking conditions right in html. For example:

The above code, when the variable time has a value, the string Time: [value] is displayed. And #noTime template is hidden, otherwise else condition is run and #noTime is displayed.

As we can see, using this ngIf else directive is very convenient when it is possible to hide html easily.

4.2 Ng-Template

It helps to gather the html to be hidden.

This way of writing is more complete than 4.1 Ng-if… else

4.3 Ng-Container

Similar to Ng-Template used to gather html. But the strong point of Ng-Container is that this directive tag does not render the html <ng-container> tag as <ng-template>, but the tag will be hidden, making the css layout not broken if you gather html (No fear of jump from parent div to child div, html structure does not change when including <ng-container> </ng-container> tag)

Consider the following example:

It will be rendered as follows:

When looking at the html we will see:

Suddenly the line div has ngIf it inserts an attribute _ngcontent-c0, resulting in the line being newline, wrong layout design.

Now rewrite the following:

The results will be beautiful right away:

That’s because the html has been neatly cleaned:

4.4 NgSwitch and NgSwitchCase

We can absolutely use the conditional statement switch case in Angular just like switch case in Javascript.

* ngSwitchDefault In case you want to use the switch case default (if all cases do not meet the screen, then go to default).

5. Attribute directive

Used as an object property, so when building, the directive and other common properties are built at the same time, leading to the directive’s changes to be concurrent when rendering that object.

5.1 Build a simple attributes directive.

Implement for directive. We can use the CLI command to create directive object.

CLI will generate src / app / highlight.directive.ts and declare it in AppModule Structure of file src / app / highlight.directive.ts

A directive attribute needs to decorate the angular’s Directive object class by using Directive before the class. The example above is HighlightDirective which aims to change the background color of an object when the user hovers over it.

Import the Directive identifier to use it decorate the object in the angular. Calling Directive before the HighlightDirective class is to use decorate, when using we need to declare the selector name to use as an attribute, [appHighlight] a ([]) is how angular understands it as an attribute. Compile that sees which element has a property named appHighlight will be applied changed by the directive. (After using Directive , don’t forget to export the HighlightDirective class so you can import and use it.)

Now let’s implement for HighlightDirective to change the background color:

ElementRef is Class in angular’s library. We use ElementRef in the construct function to inject it references to DOM elements in the current component. Then just call the ElementRef property to get the DOM object to change the background style to yellow.

5.2 Apply the directive attribute

To use HighlightDirective, add the following tags:

5.3 Directive interaction with users

Currently, appHighlight only sets a fixed color for the background, there is no flexibility and interaction. We will implement it to change the color for mouse events and user actions. First need to import HostListener.

Next is to add function handler when the event occurs using the Decorator HostListener.

HostListener decorator will track and catch the events of the element in the DOM that use the appHighlight directive The highlight function will change the background color according to the color passed in the parameter, so in the handler functions just call highlight with the argument. number is the color to display. Run and check the results offline.

5.4 Passing data into directive via Input

Currently the colors for events are still fixed, where used, the colors remain the same. To create flexibility for the directive we will pass colors to it. First, we need to import Input:

Use the decorator for the highlightColor variable.

Use appHighlight and input binding in combination for the object.

That’s the original usage, but the directive has been improved to shorten the code and is more convenient by using director as an attribute (this is why its selector has a []).

The [appHighlight] property is a combination of highlighting directive and set the variable appHighlight. We can also rename the variable if we don’t want to name the variable appHighlight according to the selector.

It is also possible to combine the above with regular input binding.

Angular will automatically understand you binding defaultColor to HighlightDirective because you have declared the Input decorator for it. binding adds a defaultColor through the input as the default color. in the handler for the mouse change event is as follows:

5.5 Complete this dummy application application.

Update the app.component.html file:

The src / app / app.component.ts file:

Conclude

My study on Directives is here to end. Hope it will be somewhat helpful for you in learning and doing about Angular . The article is also hard to avoid mistakes, hope everyone sympathizes, and hopes for everyone’s comments to make the article more complete.

References

https://angular.io/start

https://angular.io/guide/structural-directives

https://angular.io/guide/attribute-directives

Share the news now

Source : Viblo