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() bgColor: string;
@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 {
color: string = '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.
@Input('appElementHighlighter') bgColor: string;
@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