Last active
March 12, 2019 13:34
-
-
Save hollygood/9f662bf6fc4bcfa010d73097acaee859 to your computer and use it in GitHub Desktop.
Disable Angular 6 Reactive Form Fields dynamically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In Angular 6, if you set 'disabled' reactive form field like following, | |
// you will get a warning message: It looks like you're using the disabled attribute with a reactive form directive. | |
// If you set disabled to true when you set up this control in your component class, the disabled attribute will | |
// actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. | |
<input | |
formControlName="userId" | |
type="text" | |
class="form-control m-input" | |
required | |
disabled | |
/> | |
// One suggestion is using disable() function. | |
ngOnInit() { | |
this.myForm.get('userId').disable(); | |
this.myForm.get('user.emailAddress').disable(); // disable nested form field | |
} | |
// However, when you submit your form, you couldn't find the userId value in this.myForm.value | |
// disabled controls do not get included in the form.value, so you have to use the following: | |
this.myForm.getRawValue() | |
this.myForm.getRawValue().nestedForm // nested form | |
// Another way to disable this field is using [attr.disable] | |
<input | |
formControlName="userId" | |
type="text" | |
class="form-control" | |
required | |
[attr.disabled]="disableUserIdField" | |
/> | |
// component.ts | |
public disableUserIdField = null; // has to be null to not disable the field | |
if (something) { | |
this.disableUserIdField = true; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment