Communication between custom directive and component in Angular2

☆樱花仙子☆ 提交于 2019-12-05 10:22:07

You can create an @Input() someName: SomeType in your directive and bind it to a field or function in the parent component like

<div [mySelectedColor]="color" 
    [someName]="someFieldInParent"> I'm {{color}} color </div>

Another way is to query the directive in the parent component and invoke functions or set fields directly.

export class AppComponent{
  @ViewChild(selectedColorDirective) myDirective: selectedColorDirective;

  ngAfterViewInit() {
    myDirective.changeColor('red');
  }
}

You can also bind directly to class and assign CSS by using these class selectors.

See for example this http://plnkr.co/edit/nm8RgxMtqdEDyQWQGeUp?p=preview

Using a binding as selector at the same time is not supported currently, therefore you have to list the directive selector and the property you bind to each. Only [(myDirective)]="someField" seems to be supported.

I used

host: {
  '(keyup)': 'changeColor()',
  '[style.color]': 'selectedColor', // <==
}

for setting the style (I also changed the AppComponent to use this way). This is preferred to using ElementRef and Renderer. I used ElementRef and Renderer for the <span> tag though because I don't see another way from the directive on another element.

Easiest way, in your directive:

constructor(el: ElementRef) {
 el.nativeElement.style.backgroundColor = "yellow";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!