2017-05-06 37 views
2

屬性指令與功能我已屬性指令在Angular4

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); 
    } 

什麼是我必須做的屬性指令的修改,以支持新的參數,而不會使用新@輸入名稱參數? 此外,這是從Angular4的屬性指令中調用函數的正確方法嗎?

乾杯。

回答

0

使用綁定所建議

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

你不會有太大的改變。只要把參數傳送給showSimpleMessage功能的調用指令中:

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

如果不能正常工作,你可以在該函數中使用call()方法。該解決方案是,如果你想從指令調用它:

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

第一個參數null實際上是上下文this,你可以提供的功能。 'some name'是函數的參數。

另一解決方案是使用由bind() @Julia