Home > OS >  How to use property binding in custom directive?
How to use property binding in custom directive?

Time:10-31

Directive:

// highlight.directive.ts 
import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
})
export class HighlightDirective {
  @Input() yourColor: any = 'red';
  constructor(private el: ElementRef) {
    el.nativeElement.style.backgroundColor = this.yourColor;
  }
}

Consumer:

// app.component.html
<div appHighlight [yourColor]="'blue'">Testing</div>

Result:

enter image description here

Question

Why can't I pass blue to yourColor?

CodePudding user response:

You should move your code from constructor to ngOnInit. Use constructor in Angular only for injecting dependencies, but ngOnInit for executing a code when component is mounted.

Here is more info about that: Difference between Constructor and ngOnInit

CodePudding user response:

Here is a solution using two-way binding:

 // highlight.directive.ts
 export class HighlightDirective {
        yourColor: any = 'red';

        ngOnInit() {
       // change color in method
         this.yourColor = ‘blue’;
         }
       
       }

  // app.component.html
  <div appHighlight style=“background-color=    {{yourColor}}”>Testing</div>
  • Related