【发布时间】:2018-09-26 00:05:43
【问题描述】:
考虑以下代码:
<button cdtSaving type="submit" class="btn btn-default" [disabled]="!canSave()">Save</button>
用 cdt 保存一个属性指令:
@Directive({
selector: '[cdtSaving]'
})
export class SavingDirective implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private _loaderService: LoaderService, private _elRef: ElementRef, private _renderer: Renderer2) { }
ngOnInit() {
// subscribe to the service state to hide/show the loader
this.subscription = this._loaderService.loaderState
.subscribe((state: LoaderState) => {
this._renderer.setAttribute(this._elRef.nativeElement, 'disabled', state.show ? 'true' : null);
console.log(`state changed:${state.show} for element ${this._elRef.nativeElement.textContent}`);
});
}
ngOnDestroy() {
// unsubscribe
this.subscription.unsubscribe();
}
}
基本上每当调用可观察的 next() 时,我们都会启用或禁用按钮 (nativeElement)。
问题是当设置disabled属性为null时,canSave方法就不再考虑了。
因此,我想在指令中将标志设置为真/假,而不是设置禁用属性,然后我会像这样读取该标志:
<button cdtSaving type="submit" class="btn btn-default" [disabled]=" cdtSaving.myFlag || !canSave()">Save</button>
目前 cdtSaving.myFlag 不起作用,但也许有办法用 Angular 来实现?
【问题讨论】:
标签: angular angular2-directives