Web Developer

Section 7 Directive & @HostListener & @HostBinding

ng generate directive directvie-name

ng g d directive-name

@Directive({selector: ‘[directiveName]’}) export class directiveNameDirective {}

  1. @Directive({
    • selector: ‘[appHighlight]’
  2. })
  3. export class HightlightDirective implements OnInit {
    • constructor(private elementRef: ElementRef){}
    • ngOnInit() {
      • this.elementRef.nativeElement.style.backgroundColor = ‘gree’; //this will overwrite the style of the element that uses the attribute ‘appHighlight’
    • }
  4. }
  1. @Directive({
    • selector: ‘[appBetterHighlight]’
  2. })
  3. export class BetterHighlightDirective implements OnInit {
    • constructor(private elementRef: ElementRef, private renderer: Renderer2){}
    • ngOnInit(){
      • this.renderer.setStyle(this.elementRef.nativeElement, ‘backgroundColor’, ‘blue’);
    • }
  4. }

@HostListener(‘event, such as click’) handlerName() {};

@HostBinding(‘DOM property’) nameToReplace;

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>