【问题标题】:Angular 2. Bind data from directive to templateAngular 2. 将数据从指令绑定到模板
【发布时间】:2017-06-18 17:53:09
【问题描述】:

可以将数据从指令绑定到模板,指令是在哪里添加的?例如我想显示 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';
  }
}

【问题讨论】:

  • 作为问题关闭它没有意义..您可以使用组件而不是指令。为什么专门使用directive

标签: angular angular2-directives


【解决方案1】:

您可以使用exportAs 属性。它是在模板中导出组件实例的名称

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

【讨论】:

  • exportAs 用于提供一种在模板中引用指令的方法,对吗?类似&lt;form #heroForm="ngForm"&gt;&lt;input [disabled]="!heroForm.form.valid"&gt;...。它不会在父组件实例中提供任何附加值,因为即使指令没有定义 exportAs,我们也可以使用 @ViewChild(MyDir)
  • 是的,就是这样。我们可以使用@ViewChild(MyDir) 而不使用exportAs
猜你喜欢
  • 2016-05-03
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
相关资源
最近更新 更多