Angular 2. Bind data from directive to template

It's possible bind data from directive to template, where directive was add? For example I want display dirText:

[plunker][1]

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div my-dir>Text from dir: {{dirText}}</div>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Its component text`
  }
}

@Directive({
  selector: '[my-dir]'
})

export class MyDir{
  dirText: string;
  constructor(){
    this.dirText = 'Text from Dir';
  }
}

2 answers

  • answered 2017-06-17 19:25 yurzui

    You can use exportAs property. It is name under which the component instance is exported in a template

    my.directive.ts

    @Directive({
      selector: '[my-dir]',
      exportAs: 'myDir'
    })
    export class MyDir {
      ...
    

    parent.html

    <div my-dir #x="myDir">Text from dir: {{x.dirText}}</div>
    

    Plunker Example

  • answered 2017-06-17 19:25 LuckyHamster

    Thank you very much! It's helped me!