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,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,this.selectedColor); } changeColor(color:string) { console.log('Changed Detection' + " " + selectedColor); //this.renderer.setElementStyle(this.el,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'); } } 您还可以直接绑定到类并使用这些类选择器分配CSS. 参见例如http://plnkr.co/edit/nm8RgxMtqdEDyQWQGeUp?p=preview 目前不支持同时使用绑定作为选择器,因此您必须列出指令选择器和绑定到每个指令选择器的属性.似乎只支持[(myDirective)] =“someField”. 我用了 host: { '(keyup)': 'changeColor()','[style.color]': 'selectedColor',// <== } 用于设置样式(我还改变了AppComponent以这种方式使用).这是使用ElementRef和Renderer的首选.我使用ElementRef和Renderer作为< span>标签,因为我没有看到另一个元素的指令的另一种方式. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |