has anyone created any sample Angular Directive using @Directive
decorator? I searched a lot on however all developers so far created component directives. Even Angular API Review doesn't speak more on this.
Simple-Directive-Demo . This is a very simple example to start with angular2 directive.
I have a component and directive.
I use directive to update component's view. Moreover directive's changeColor function is getting called with a component's changeColor function.
Component
@Component({
selector: 'my-app',
host: {'[style.backgroundColor]':'color',}
template: `
<input type="text" [(ngModel)]="color" (blur)="changeColor(color)" />
<br>
<span > (span) I'm {{color}} color <span>
<div mySelectedColor [selectedColor]="color"> (div) I'm {{color}} color </div>
`,
directives: [selectedColorDirective]
})
export class AppComponent implements AfterViewInit{
@ViewChild(selectedColorDirective) myDirective: selectedColorDirective;
color:string;
constructor(el:ElementRef,renderer:Renderer) {
this.color="Yellow";
//renderer.setElementStyle(el, 'backgroundColor', this.color);
}
changeColor(color)
{
this.myDirective.changeColor(this.color);
}
ngAfterViewInit() { }
}
Directive
@Directive({
selector:"[mySelectedColor]",
host: {
// '(keyup)': 'changeColor()',
// '[style.color]': 'selectedColor',
}
})
export class selectedColorDirective {
@Input() selectedColor: string = '';
constructor(el: ElementRef, renderer: Renderer) {
this.el=el;
this.el.nativeElement.style.backgroundColor = 'pink';
// renderer.setElementStyle(el, 'backgroundColor', this.selectedColor);
}
changeColor(clr)
{
console.log('changeColor called ' + clr);
//console.log(this.el.nativeElement);
this.el.nativeElement.style.backgroundColor = clr;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With