Angular 4 : 从主机访问属性指令
Angular 4 : Access attribute directive from host
考虑以下代码:
<button cdtSaving type="submit" class="btn btn-default" [disabled]="!canSave()">Save</button>
用 cdtSaving 属性指令:
@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
方法不再被考虑
所以我想在指令中将标志设置为 true/false 而不是设置禁用属性,然后我会像这样读取该标志:
<button cdtSaving type="submit" class="btn btn-default" [disabled]=" cdtSaving.myFlag || !canSave()">Save</button>
目前 cdtSaving.myFlag 行不通,但也许有一种方法可以通过 Angular 实现?
如果要访问指令内部状态,需要在 @Directive()
装饰器中设置 exportAs
元数据。
此外,ElementRef
和 Renderer
也不需要对 disabled
属性进行命令式管理。只需使用 @HostBinding
装饰器即可。
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[cdtSaving]',
exportAs: 'cdtSaving'
})
export class SavingDirective {
myFlag = false
}
用法:
<button cdtSaving #dir="cdtSaving" [disabled]="dir.myFlag">Save</button>
考虑以下代码:
<button cdtSaving type="submit" class="btn btn-default" [disabled]="!canSave()">Save</button>
用 cdtSaving 属性指令:
@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
方法不再被考虑
所以我想在指令中将标志设置为 true/false 而不是设置禁用属性,然后我会像这样读取该标志:
<button cdtSaving type="submit" class="btn btn-default" [disabled]=" cdtSaving.myFlag || !canSave()">Save</button>
目前 cdtSaving.myFlag 行不通,但也许有一种方法可以通过 Angular 实现?
如果要访问指令内部状态,需要在 @Directive()
装饰器中设置 exportAs
元数据。
此外,ElementRef
和 Renderer
也不需要对 disabled
属性进行命令式管理。只需使用 @HostBinding
装饰器即可。
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[cdtSaving]',
exportAs: 'cdtSaving'
})
export class SavingDirective {
myFlag = false
}
用法:
<button cdtSaving #dir="cdtSaving" [disabled]="dir.myFlag">Save</button>