【问题标题】:Attribute Directive with function in Angular4Angular4中具有功能的属性指令
【发布时间】:2017-05-06 12:24:32
【问题描述】:

我有以下属性指令

import { Directive,HostListener,Input } from '@angular/core';

@Directive({
  selector: `[appConfirmaction]`
})
export class ConfirmactionDirective {
  @Input() appConfirmaction = () => {};
  @Input() confirmMessage = 'Do you want to keep going?';

  @HostListener('click', ['$event'])
  confirmFirst() {
    const confirmed = window.confirm(this.confirmMessage);

    if(confirmed) {
      this.appConfirmaction();
    }
  }
}

那我在一个按钮中使用上面的指令属性,比如

<button md-icon-button [appConfirmaction]="showSimpleMessage" >

组件的功能代码为:

showSimpleMessage(){
    alert("Hello");
  }

这段代码完美运行。

现在,假设我要给函数showSimpleMessage添加一个参数,比如

showSimpleMessage(name:string){
    alert("Hello "+name);
  }

在不为 name 参数使用新 @Input 的情况下,我必须对属性指令进行哪些更改以支持新参数? 另外,这是使用 Angular4 从属性指令调用函数的正确方法吗?

干杯。

【问题讨论】:

    标签: javascript angular angular2-directives


    【解决方案1】:

    使用绑定

      <button  [appConfirmaction]="showSimpleMessage.bind(null, 'Julia')" >
           click me 
      </button>
    

    【讨论】:

      【解决方案2】:

      你不必改变太多。只需在指令中为您调用showSimpleMessage 函数添加参数即可:

      if(confirmed) {
        this.appConfirmaction('some name');
      }
      

      如果这不能正常工作,您可以在该函数上使用call() 方法。这个解决方案是如果你想从指令中调用它:

      if(confirmed) {
        this.appConfirmaction.call(null, 'some name');
      }
      

      第一个参数null 实际上是您可以提供给函数的上下文this'some name'是函数的参数。

      另一种解决方案是按照@Julia 的建议使用bind()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-26
        • 2016-02-04
        • 1970-01-01
        • 1970-01-01
        • 2020-08-24
        相关资源
        最近更新 更多