2016-08-30 43 views
1

我做了如下指令被刷新:指令時,需要輸入變化

import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core'; 
import { Observable, Subscription } from 'rxjs/Rx'; 

@Directive({ 
    selector: '[myDisabled]' 
}) 

export class DisableDirective implements OnInit { 
    private el: HTMLElement; 

    @Input('myDisabled') isDisable: boolean; 

    constructor(el: ElementRef) { this.el = el.nativeElement;} 

    ngOnInit() { 
     this.disable(); 
    } 

    private disable() { 
     this.isDisable ? this.el.style.opacity = '0.65' : this.el.style.opacity = '1'; 
    } 
} 

此指令設置一個按鈕的不透明度取決於輸入:isDesable。這個設置需要在輸入改變時刷新,但是,我不知道該怎麼做。

我使用這個指令是這樣的:

<button class="btn" [myDisabled]="!sharedDetails.isEnabled">A button !</button> 

回答

0

兩種方式

_isDisabled: boolean; 
@Input('myDisabled') 
set isDisable(value: boolean) { 
    this._isDisabled = value; 
    this.disable(); 
} 

// called every time after inputs are updated 
// check the `changes` parameter for details if you have more than one input 
ngOnChanges(changes) { 
    this.disable();  
} 
+1

試了第二種方式,完美地工作,只需要導入OnChanges。謝謝 ! –

+1

也嘗試了第一種方式,工作以及但我需要刪除設置器的「:無效」 –

+0

偉大的,感謝您的反饋(不積極使用TS自己)。 –