Hongbo Miao
Hongbo Miao

Reputation: 49744

How to pass a value into the Directive?

I have a Directive:

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

Can I pass a value text into the Directive?

<div random></div>

Thanks

Upvotes: 0

Views: 293

Answers (2)

micronyks
micronyks

Reputation: 55443

Plunker - check console.

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";  
}

Upvotes: 3

Kayo Lima
Kayo Lima

Reputation: 740

Try this:

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

Directive:

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

  @Input() text: string;

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

Upvotes: 4

Related Questions