Sunday 3 May 2020

Angular 8 Session 18 - Custom Attribute Directive With Input Decorator

Custom Attribute Directive With Input Decorator

* @Input is a decorator which makes a class filed as Input Property.
* It bound to a DOM property in template and while running it updates the input  field with DOM property value.
* Input decorator is a part of @angular/core library. 
@Input() bgColor:string;

Using @Input 

Step-1: Modify elementhighlighter.directive.ts as below with introduction of an input field.
@Input() bgColorstring;

@HostListener('mouseenter'onMouseEnter() {
  this.takeEffect(this.bgColor || 'green');
};
Step-2: Create a field in app.component.ts to assign a color to directive.
export class AppComponent {
  colorstring = 'pink';
};

Step-3: Modify the UI as below with use of newly created @Input property.
<div>
  <div appElementHighlighter [bgColor]='color'>This tutorial elaborates custom directive</div>
  <br />
  <p appElementHighlighter>This is SKMDotNet Tutorial.</p>
</div>

Using @Input With Alias 

* An alias name can be given with any name, but here we are using same as directive selector to avoid confusion.

Step-1: Modify elementhighlighter.directive.ts as below with alias name to an input field.
@Input('appElementHighlighter'bgColorstring;

  @HostListener('mouseenter'onMouseEnter() {
    this.takeEffect(this.bgColor || 'green');
  }

Step-2: Modify app.component.html to bind the property using alias name.
<div>
  <div [appElementHighlighter]='color'>This tutorial elaborates custom directive</div>
  <br />
  <p appElementHighlighter>This is SKMDotNet Tutorial.</p>
</div>

No comments:

Post a Comment

Angular 8 Session 21 - ngFor Directive In Angular

ngFor Directive Content will be resume soon. Stay tuned!