Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Directive

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.

like image 432
Avi Kenjale Avatar asked Jan 27 '16 21:01

Avi Kenjale


1 Answers

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;
     }

 }
like image 140
Nikhil Shah Avatar answered Oct 15 '22 00:10

Nikhil Shah