You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
9 Hrs
25 Min
30 Seg

Conociendo las directivas

17/20
Resources

Angular uses the concept of directive to change the appearance or behavior of an element in the HTML. Here we will be learning about directives.

Your first directive

To create your first directive, you need to use the Angular CLI with the command ng generate directive test-name or in its short form ng g d test-name.

As with services and pipelines, the CLI command will create a .ts file with your directive code and a .spec.ts file for their respective unit tests.

The CLI will also update the app.module.ts file by importing the directive into the declarations[]. Don't forget to make sure it is being imported correctly. Otherwise, Angular will not recognize the directive.

The default directives look like this:

import { Directive } from '@angular/core'; @Directive({ selector: '[appTestName]'})export class TestNameDirective {  constructor() { } }

They use the @Directive() decorator that contains the name you will use in the HTML to use the directive.

Manipulating styles

In the directives, you can capture the HTML element by importing the ElementRef service and thus be able to change the styles of that element:

// directives/change-color.directive.tsimport { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appChangeColor]'})export class ChangeColorDirective {  constructor( private element: ElementRef ) { this.element.nativeElement.style.color = 'blue'; } } }
<div> <p appChangeColor>Textcolor blue.</p></div>

Listening to events

Another possibility offered by directives, is listening for events. Making use of the @HostListener() decorator and imported from @angular/core you can execute a function every time a click, hover, scroll or any other event occurs.

// directives/change-color.directive.tsimport { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appChangeColor]'})export class ChangeColorDirective { @HostListener('mouseenter') onMouseEnter() { this.element.nativeElement.style.color = 'blue'; } @HostListener('mouseleave') onMouseLeave() { this.element.nativeElement.style.color = ''; } constructor( private element: ElementRef ) { } } }
<div> <p appChangeColor>Textcolored blue when hovering.</p></div>

Passing data to a directive

Finally, if you have a need for your directive to receive some kind of value, it's best to rely on the decorator you already know @Input().

// directives/change-color.directive.tsimport { Directive, Input, ElementRef } from '@angular/core'; @Directive({ selector: '[appChangeColor]'})export class ChangeColorDirective { @Input() color!: string; constructor( private element: ElementRef ) { this.element.nativeElement.style.color = this.color; } } }
<div> <p appChangeColor [color]="'blue'">Textcolor blue.</p></div><div> <div> <p appChangeColor [color]="'red'">Textcolor red.</p></div><div> <div> <p appChangeColor [color]="'green'">Textcolor green.</p></div><div> <p

It can be somewhat difficult if you're just starting out with Angular to imagine a good use for a directive of your own. For now, it's important to know they exist so you can implement them when that time comes.

View project source code


Contribution created with contributions from Kevin Fiorentino.

Contributions 10

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

Un ejemplo mas podria ser de utlizar una directica que escuche el evento error de una imagen si para luego poner a dicha imagen una imagen por default

@Directive( { selector: '[imageError]' } )
export class ImageErrorDirective {

//escucha el evento error
  @HostListener( 'error' )
  handleError (): void {
    this.elment.nativeElement.src = "https://www.sam-manipulados.com/wp-content/uploads/2014/01/default_image_01.png";
  }

  constructor(
    private elment: ElementRef<HTMLImageElement>
  ) {
    console.log( elment );
  }
}

//template
<img imageError width="100px" [src]="image" alt="">

Entonces las directivas se usan solo para modificar el DOM, pero no es recomendable hacer estas modificaciones al DOM de está manera según la documentación de Angular. Lo que quiere decir que no tiene mucha utilidad crear directivas.

Estoy en lo correcto?

Directivas

Las directivas se usan para modificar el DOM de forma directa y también se pueden modificar los atributos.

Aplicar cambios al nativeElement no se recomienda con hacer así.
Es mejor usar Render2

https://angular.io/api/core/Renderer2

DIRECTIVE

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  @HostListener('mouseenter') onMouseEnter() {
    this.element.nativeElement.style.backgroundColor = 'red';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.element.nativeElement.style.backgroundColor = '';
  }

  constructor(
    private element: ElementRef
  ) {
    // this.element.nativeElement.style.backgroundColor = 'red';
  }

}

HTML

// insertarlo como un atributo dentro del elemento
<p appHighlight>{{ product.description }}</p>

En la pestaña recursos tienen mal el comando, suelo leerlo antes de ver el video y me confundió un poco.

Aplicando esta direcctiva puedes afectar los inputs directamente de un formulario es decir cambiar las palabras directamente.

import { Directive, ElementRef, HostListener } from@angular/core’;

@Directive({
selector: ‘[appOnlyNumbers]’
})
export class OnlyNumbersDirective {

@HostListener(‘input’,) onChangueinput(){
this.element.nativeElement.value = this.element.nativeElement.value.replace(/a/gi, “4”)
}

constructor(
private element: ElementRef
) {
// element.nativeElement.value = this.element.nativeElement.value.replace(/a/gi, “4”)
}

}

Conclusión: Las directivas en Angular pueden ser muy útiles cuando necesitas integrar librerías externas que operan directamente con JavaScript puro

directivas son para modificar el DOM ng g d directives/hightlight

Conociendo las directivas

Las directivas son decoradores para modificar el DOM y atributos.

Creamos las directivas con la CLI: ng g d directives/highlight