如何将值传递给指令?

时间:2016-06-03 00:12:55

标签: typescript angular

我有一个指令:

@Directive({
  selector: 'random'
})
export class RandomDirective {
  @Input text: string;
}

我可以将值text传递给指令吗?

<div random></div>

由于

2 个答案:

答案 0 :(得分:4)

试试这个:

<div random [text]="'sometext'"></div>

指令:

@Directive({
  selector: '[random]',
  host: {
    '(mouseenter)': 'onMouseEnter()', //just for test
  }
})
export class RandomDirective {

  @Input() text: string;

  //method for test
  onMouseEnter() {
   console.log(this.text);
  }
}

答案 1 :(得分:3)

Plunker - 检查控制台。

import {Component, Directive, Input} from 'angular2/core'

@Directive({
    selector: '[random]'
})
export class RandomDirective implements OnChanges {

  @Input() text:string;

   ngOnChanges(...args: any[]) {
        console.log('onChange fired');
        console.log(args[0].text)
    }
}



@Component({
  selector: 'my-app', 
  providers: [],
  template: `

    <p random  [text]="value"></p>
  `,
  directives: [RandomDirective]
})

export class App {
  value:string="micronyks";  
}