如何从父访问 attr 指令中的函数? (角度2)

How to access function inside attr directive from parent? (Angular2)

我希望能够通过父级中的用户交互访问我的 attr 指令中的函数。我准备了一个plunk来演示;

https://plnkr.co/edit/MZONsuh7O6bWgZfE0mZ2?p=preview

在此示例中,当用户在输入中键入内容时会触发一个事件。我想知道一旦发生这种情况是否有可能同时触发 attr 指令中的 onChange() 函数?

不确定如何实现,欢迎任何建议!

谢谢,

下面的代码


app.ts

@Component({
  selector: 'my-app',
  template: `
      <div testGenerator></div>
      <input type="text" (input)="detectChange($event)" />
  `,
})
export class App {

  constructor() {
  }

  detectChange(e){
    console.log(e.target.value)
  }

}

测试指令:

import {Directive} from '@angular/core';

@Directive({
  selector: '[testGenerator]'
})
export class TestDirective {

  constructor() {
  }

  onChange(){
    console.log("hello")
  }
}

最简单的方法是使用指令 exportAs 选项和模板引用。参见 plunkr

您可以使用 ViewChild API 从父组件调用指令的函数,如下所示,

演示版:https://plnkr.co/edit/zDVtxuzNPssxzBlpozjv?p=preview

export class App {
  @ViewChild(TestDirective) vc:TestDirective;  //<<<---added

  constructor() {
  }

  detectChange(e){
    console.log(e.target.value)
    this.vc.onChange();                        //<<<---added
  }

}

Template-driven的解决办法也是可以的。将 inputValue 绑定到 Directiveplunkr