微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>标签,因为我没有看到另一个元素的指令的另一种方式.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐