2

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';
  }
}
1
  • Closing it as the question is not meaningful.. you can use a component instead of directive. why specifically you use directive? Commented Jun 17, 2017 at 19:26

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

the exportAs is used to provide a way to reference a directive in a template, correct? something like <form #heroForm="ngForm"><input [disabled]="!heroForm.form.valid">.... It doesn't provide any additional value inside the parent component instance since we can use @ViewChild(MyDir) even if the directive doesn't define exportAs?
Yes, that is. We can use @ViewChild(MyDir) without exportAs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.