Directives In Angular – Part One (Attribute Directives)

What are Directives?

Directives are elements which change the appearance or behavior of the DOM element. There are 3 types of the Directives mainly. We have categorized them, as follows –

Components are the Directives, according to Angular documentation, and have their own templates. To know more about Components, you can find these articles at the following locations.

The above topics cover all the needed details about the components. Let’s explore the Attribute directive in details in this article.

Attribute Directives

Attribute directive is a way to modify the appearance of the DOM element or component. There are 2 built-in Attribute Directives in Angular. Let’s see them one by one.

NgStyle Attribute Directive

Angular provides a built-in NgStyle attribute to modify the element appearance and behavior. Let’s add a new component and name it ngStyleComponent by using ng generate component command. Now, let’s look at the snippet of the component.

import {  
    Component,  
    OnInit  
} from '@angular/core';  
@Component({  
    selector: 'app-ng-styles',  
    templateUrl: './ng-styles.component.html',  
    styleUrls: ['./ng-styles.component.css']  
})  
export class NgStylesComponent implements OnInit {  
    applygreenstyle: boolean = true;  
    borderStyle = '1px solid black';  
    appStyleGreen = {  
        'color': 'green',  
        'font-weight': 'bold',  
        'font-size': '45px',  
        'borderBottom': this.borderStyle,  
        'padding': '1rem'  
    };  
    appStyleBlue = {  
        'color': 'blue',  
        'font-weight': 'bold',  
        'font-size': '45px',  
        'borderBottom': this.borderStyle,  
        'padding': '1rem'  
    };  
    ChangeColor(): void {  
        this.applygreenstyle = !this.applygreenstyle;  
    }  
    constructor() {}  
    ngOnInit() {}  
}  

Here, we have added the component and we have defined the properties applystyleGreen and the applystyleBlue along with two properties applygreenstyle and borderstyle . We can see how to use them via a template of the component that is the HTML file.

Assigning Inline style to ngStyle

set style from the Component.

Change the Style based On Condition..

In all the above cases, we have assigned the properties from the component to the [NgStyle ] attribute of the Angular. First is the inline way of assigning. In that, we have used the property borderStyle from the component which has the value from the component. Along with that, we have assigned the property appstylegreen from the component directly to the [ngStyle] attribute. Third, we have added one button and based on the condition of the variable applygreenstyle, we are changing the value of the

tag.

One thing that we need to consider here is that we are assigning the values to the [ngstyle] attribute the same way we bind the attribute in the component. In the first case, we have used the object literal to assign NgStyle. NgStyle accepts the object where the object defines the element style and the properties properly. Next, we can see that we have assigned the object properties from the component to the NgStyle. Here, we can make use of the property binding concept of Angular.

ngClass Attribute Directive

This attribute is used to change the class attribute of the element in DOM or the component to which it has been attached. There are a few ways we can achieve this. Let us see them with the following code snippet.

  
    .lefttext {  
        text-align: left;  
        width: 500px  
    }  
  
    .backcolor {  
        background-color: navajowhite;  
    }  
  
    .textfont {  
        font-size: 40px;  
        font-family: 'Times New Roman', Times, serif  
    }  
  
    .centertext {  
        text-align: center;  
        width: 700px;  
        color: navajowhite;  
    }  
  
    .secondparabgcolor {  
        background-color: blueviolet  
    }  
  
    .secondparafont {  
        font-weight: bolder;  
        font-size: 35px  
    }  
  
    .borderandBox {  
        border: 1px solid #eee;  
        padding: 1rem;  
        margin: 0.4rem;  
        font-family: sans-serif;  
        box-shadow: 2px 2px 2px #888888;  
    }  
  
    .dark {  
        background-color: #444;  
        border-color: #000;  
        color: #fff;  
    }  
  
    .changefont {  
        font-size: 80px;  
        background-color: navajowhite;  
        text-align: left;  
    }  
  

Assigning as a string ...

assigning as array

Assigning as Object.

In this snippet, we have defined some style element and we have used them in different ways.

  1. Assigning as a string
    When we see the first paragraph, we have assigned the string lefttext, backcolor, and textfont to the ngClass directive.
  2. Assigning as an Array

    In the second paragraph, we have passed the array to the ngClass. Here, we can pass the array object properties separated by a comma and enclosed.

  3. Assigning as an Object
    In the last paragraph, we can assign the object to the directives directly. Angular applies each property to the element if it is true. In the third example, we have seen that we have assigned the false true as a value to the property to the elements and we can see that the output is changing accordingly.

Creating Attribute Directives

So far, we have seen the built-in attribute directives in Angular. Let’s see how we can create the Attribute directives manually.

For that, let us use the command ng g directives [nameofdirective] in the command prompt and we can see the added directive in our application code snippet.

import {  
    Directive,  
    ElementRef  
} from '@angular/core';  
@Directive({  
    selector: '[appTextcolor]'  
})  
export class TextcolorDirective {  
    constructor(elementr: ElementRef) {  
        elementr.nativeElement.style.color = 'Red';  
        elementr.nativeElement.style.fontSize = '40px';  
    }  
}  

Let’s understand some basic stuff about how this Directive works.

  1. The class which we are going to use must be decorated with the @Directive attribute. This is used to mark as a directive for the Angular class.
  2. In metadata section of the directive, we use the selector and assign the directive name to that selector.
  3. In Constructor, we define the element reference by using the DI. By using the element reference, we can access the DOM element properties and use them accordingly.
  4. The final step would be to use the Directive in the app module so that it will be available in the application.

So to use this directive in the application, we just need to modify our template like in the below snippet.

Changing the color using Directives.

Here, we have seen that we are using this decorator for the paragraph element. When we see the output, we see that the content size is increased to 40px and the font color is Red.

Let’s create the Directive to change the text color, size, and background color. When we see the snippet of the component, we can see the code as below.

import {  
    Directive,  
    ElementRef  
} from '@angular/core';  
@Directive({  
    selector: '[appTextcolor]'  
})  
export class TextcolorDirective {  
    constructor(elementr: ElementRef) {  
        elementr.nativeElement.style.color = 'blue';  
        elementr.nativeElement.style.fontSize = '40px';  
        elementr.nativeElement.style.backgroundColor = 'black';  
    }  
}  

Let’s see some ways to create and use the Attribute Directives. The first of them all is using the @Input Binding property and by using the Hostlistener in the Directives.

Attribute Directive using @Input

To use the Attribute Directive using the @Input, let’s understand what is @Input. This is the decorator which can be used to pass the values from the child to parent.

So, while using this, we can see how we can use it. Let us check the snippet here.

import {  
    Directive,  
    ElementRef,  
    Input,  
    AfterViewInit  
} from '@angular/core';  
@Directive({  
    selector: '[appTextcolor]'  
})  
export class TextcolorDirective implements AfterViewInit {  
    ngAfterViewInit(): void {  
        this.elementr.nativeElement.style.color = this.textColor;  
        this.elementr.nativeElement.style.fontSize = this.textsize;  
    }  
    @Input() textColor: string;  
    @Input() textsize: string  
    constructor(private elementr: ElementRef) {}  
}  

Here, the event which we use to check the initialization of the View is the NgAfterViewInit. This is the hook which will be called when all the views are initialized in the application. To use them in the template, we can do the following.

Changing the color using Directives.

Here, what we are doing is assigning the textcolor, textsize values which will be bound to the variables in the Dierectives and it applies the values to the elements in directives.

This is custom attribute directive using the @Input Directive. Let us see another way of doing this.

Attribute directives using @HostListener

In most of the cases, there is a need to change the appearance or the behavior of the element based on the event that is fired from the DOM element. In that case, we can use the @Host listener. Hostlistener is used to listen to any event which is fired in the DOM.

Let’s see how we can use the Hostlistener and we can make use of them step by step.

import {  
    Directive,  
    HostListener,  
    ElementRef  
} from '@angular/core';  
@Directive({  
    selector: '[appApphostlistener]'  
})  
export class ApphostlistenerDirective {  
    @HostListener('mouseleave') onmosueleave() {  
        this.changecolor("Blue");  
    }  
    @HostListener('mouseover') onmouseover() {  
        this.changecolor("Red");  
    }  
    @HostListener('click') clicked() {  
        this.changecolor("Green");  
    }  
    changecolor(colorname: string): void {  
        this.elem.nativeElement.style.color = colorname;  
    }  
    constructor(private elem: ElementRef) {}  
}  

Here, we have used the @Hostlistener Directive that is used to listen to the events happening at the template. We checked for the mouseover, mouseleave, and the click event at the hostlistener. This was all about creating the custom attribute directive and using them in the template of the component.

Note

Please run
npm install before running this application.

References

  • https://angular.io/
  • https://rangle.io/
C-Sharpcorner稿源:C-Sharpcorner (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Directives In Angular – Part One (Attribute Directives)

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录