Directives

Directives

Directives are classes that add additional behavior to elements in your Angular applications.
There are three types of directives provided by angular:
1.Attribute Directives
2.Component Directives
3. Structural Directives


1.Attribute Directives:

It is an directives which enables us to change  the appearance or behavior of DOM elements and Angular components with attribute directives.

CLI for Directives  : ng 
generate directive highlight

eg:

import {Directive, ElementRef, inject} from '@angular/core';
@Directive({
    selector: '[appHighlight]',

})

export class HighlightDirective {
    private el = inject(ElementRef);
    constructor() {
            this.el.nativeElement.style.backgroundColor = 'yellow';
            }
   }


where 
The  @Directive() decorator's configuration property specifies the directive's CSS attribute selector, [appHighlight].

Import ElementRef from @angular/core. ElementRef grants direct access to the host DOM element through its nativeElement property.

Add ElementRef in the directive's constructor() to inject a reference to the host DOM element, the element to which you apply appHighlight.

Add logic to the HighlightDirective class that sets the background to yellow.

import {Directive, ElementRef, inject} from '@angular/core';

@Directive({
                    selector: '[appHighlight]',
                    })

export class HighlightDirective {
                                    private el = inject(ElementRef);
                                    constructor() {
                                    this.el.nativeElement.style.backgroundColor = 'yellow';
                                    }
                     }



templete:
<p appHighlight>Highlight me!</p>


Comments

Popular posts from this blog

Angular Guides Notes

SIGNALS