I want to make <input>
which using material matInput
to become readonly using my custom directive. The directive isControlReadonly
will be used to set readonly based on security criteria. The problem is it works on <input>
but has no effect on <input matInput>
So.. this first input works, the second doesn't:
<!-- this works -->
<input type="input" formControlName="test_field" isControlReadonly>
<!-- this doesn't works -->
<mat-form-field appearance="standard">
<mat-label>Name</mat-label>
<input matInput type="input" formControlName="customer_name" isControlReadonly>
</mat-form-field>
This is the directive:
import { Directive, ElementRef, OnInit, ViewChildren } from '@angular/core';
import { SecurityService } from './security.service';
@Directive({selector: '[isControlReadonly]'})
export class IsReadonlyDirective implements OnInit {
constructor(
private elementRef: ElementRef,
private securityService: SecurityService
) { }
ngOnInit(): void {
var ro = !this.securityService.user.canEdit
this.elementRef.nativeElement.setAttribute('readonly', ro)
}
Please help how to make that custom directive works with matInput?
Edit Note: I don't want to set readonly from reactive form since directive is much cleaner code. I don't want to add logic to my component, I want the logic in the directive since it is centralized and will be used on all forms.
Thanks