I already tried to follow the example of other answers from here and I did not succeed!
I created a reactive form (ie, dynamic) and I want to disable some fields at
name: [{value: '', disabled: true}, Validators.required],
name: [{value: '', disabled: this.isDisabled}, Validators.required],
or
this.form.controls['name'].disable();
The best solution is here:
https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110
Outline of solution (in case of broken link):
(1) Create a directive
import { NgControl } from '@angular/forms';
@Directive({selector: '[disableControl]'})
export class DisableControlDirective {
@Input() set disableControl( condition : boolean ) {
const action = condition ? 'disable' : 'enable';
this.ngControl.control[action]();
}
constructor( private ngControl : NgControl ) {}
}
(2) Use it like so
<input [formControl]="formControl" [disableControl]="condition">
(3) Since disabled inputs do not show in form.value on submit you may need to use the following instead (if required):
onSubmit(form) {
const formValue = form.getRawValue() // gets form.value including disabled controls
console.log(formValue)
}
It is bad practice to use disable in a DOM with reactive forms.
You can set this option in your FormControl
, when you init the from
username: new FormControl(
{
value: this.modelUser.Email,
disabled: true
},
[
Validators.required,
Validators.minLength(3),
Validators.maxLength(99)
]
);
Property value
is not necessary
Or you can get your form control with get('control_name')
and set disable
this.userForm.get('username').disable();
lastName: new FormControl({value: '', disabled: true}, Validators.compose([Validators.required])),
If you want to disable first
(formcontrol) then you can use below statement.
this.form.first.disable();
This worked for me:
this.form.get('first').disable({onlySelf: true});