【问题标题】:How to access function inside attr directive from parent? (Angular2)如何从父级访问 attr 指令中的函数? (角2)
【发布时间】:2017-01-26 13:24:28
【问题描述】:

我希望能够通过父级中的用户交互来访问我的 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")
  }
}

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以使用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
        }
      
      }
      

      【讨论】:

        【解决方案3】:

        模板驱动的解决方案也是可能的。将inputValue 绑定到Directiveplunkr

        【讨论】:

          猜你喜欢
          • 2016-01-25
          • 1970-01-01
          • 2017-01-28
          • 2016-07-07
          • 2017-06-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-29
          相关资源
          最近更新 更多