Angular2中自定义指令和组件之间的通信

Communication between custom directive and component in Angular2

我有一个模板,其中包含文本框、一个 'span' 标签和一个 'div' 标签。

'div' 标签有 'selectedColor' 自定义指令。我想在更改输入值时更改 'span' 和 'div' 标签的背景颜色。

所以最后我希望我的指令对输入变化做出反应并设置 'div' 标签的背景颜色。

我还想更改 'span' 输入值更改事件的背景颜色。

Plunker

boot.ts

import {Component,bind} from 'angular2/core';

import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';
import {selectedColorDirective} from 'src/directive';
import {Directive, ElementRef, Renderer, Input} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
      <input type="text" [(ngModel)]="color"  />
      <br>
      <span > I'm {{color}} color <span>
      <div [mySelectedColor]="color"> I'm {{color}} color </div>
    `,
    directives: [selectedColorDirective]
})

export class AppComponent{

  color:string;
  constructor(el:ElementRef,renderer:Renderer)
  {
    this.color="Yellow";
    renderer.setElementStyle(el, 'backgroundColor', this.color);
  }
 }

    bootstrap(AppComponent, []);

directive.ts

import {Directive, ElementRef, Renderer, Input} from 'angular2/core';

@Directive({

  selector:"[mySelectedColor]", 
    host: {
    // '(keyup)': 'changeColor()',
    '(blur)': 'changeColor()',
  }

  })

  export class selectedColorDirective{ 

    @Input('mySelectedColor') selectedColor: string;

    constructor(el: ElementRef, renderer: Renderer) {
        //el.nativeElement.style.backgroundColor = 'yellow'; 
       renderer.setElementStyle(el, 'backgroundColor', this.selectedColor);
    } 

    changeColor(color:string)
    {
       console.log('Changed Detection' + " " + selectedColor);
       //this.renderer.setElementStyle(this.el, 'backgroundColor', this.color);
     }
  }

此外,如果你能解释更多关于@Input 装饰器的信息。

您可以在指令中创建一个 @Input() someName: SomeType 并将其绑定到父组件中的字段或函数,例如

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

另一种方式是在父组件中查询指令,直接调用函数或设置字段。

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

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

您还可以直接绑定到 class 并使用这些 class 选择器分配 CSS。

例如,参见此 http://plnkr.co/edit/nm8RgxMtqdEDyQWQGeUp?p=preview

目前不支持同时使用绑定作为选择器,因此您必须列出指令选择器和绑定到每个的 属性。似乎只支持 [(myDirective)]="someField"

我用过

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

用于设置样式(我也将 AppComponent 更改为使用这种方式)。这优于使用 ElementRefRenderer。我使用 ElementRefRenderer 作为 <span> 标记,因为我没有从另一个元素的指令中看到另一种方式。

最简单的方法,在你的指令中:

constructor(el: ElementRef) {
 el.nativeElement.style.backgroundColor = "yellow";
}