I'm looking for a way to get the disabled
attribute of the projected with <ng-content>
input
. For being able to change the host element's behavior accordingly.
<host-cmp>
<input type="checkbox" [(ngModel)]="value" [disabled]="condition">
</host-cmp>
Also, I don't think it's a good idea to repeat condition
as an @Input
for <host-cmp>
, even if it makes life much easier...
The solution I've ended up with (so far, searching a lot...) is the following:
- Create a directive for input, get attribute with
MutationObserver
- Grab this directive with
@ContentChild
inside the host.
// in <host-cmp>
@ContentChild(InputRefDirective, {static: false}) input: InputRefDirective;
get disabled() {
return this.input.disabled;
}
// InputRefDirective
@Directive({
selector: 'input[type=checkbox]'
})
export class InputRefDirective implements OnDestroy {
public disabled: boolean;
private observer: MutationObserver;
constructor(private el: ElementRef) {
this.observer = new MutationObserver(([record]) =>
this.disabled = (record.target as HTMLInputElement).disabled);
this.observer.observe(this.el.nativeElement, {
attributeFilter: ['disabled'],
childList: false,
subtree: false
});
}
ngOnDestroy(): void {
this.observer.disconnect();
}
}
It works perfectly fine, but I have doubts... Isn't it too "heavy" for the task like this? Maybe, I've missed something and this could be done in a more Angular-ish way?