'Cannot assign to 'value' because it is a constant or a read-only property. Angular 6
I am trying to set a value to a Mat input using FormControl
<input name="contact" matInput [matAutocomplete]="contactAuto" [formControl]="myControl" #contact (blur)="validateInput($event, contact.value)" >
In my Ts
myControl = new FormControl();
this.myControl.value = 'contact';
The above code is working fine but I get an error
Cannot assign to 'value' because it is a constant or a read-only property
Am I missing something here?
Solution 1:[1]
It's not allowed to set value like you are trying. You need to either use setValue or patchValue methods.
https://angular.io/api/forms/FormControl#setvalue
https://angular.io/api/forms/FormControl#patchvalue
For FormControl they're identical, but those methods work differently for i.e. FormGroup.
Solution 2:[2]
That is not the way to set value. Correct way to set is using setValue() or patchValue()
this.myControl.setValue('contact');
Solution 3:[3]
In terms of contact form to make it invalid manually this one worked for me this.contactForm.setErrors({ valid: false });
Solution 4:[4]
You can use setValue
or patchValue
to achieve this. The difference is as follows.
PatchValue
is used to update only a subset of the elements of the FormGroup or FormArray. It will only update the matching objects and ignores the rest.SetValue
is used to update the FormControl , FormGroup or FormArray. When we use it to update the FormGroup or FormArray the SetValue requires that the object must match the structure of the FormGroup or FormArray exactly. Otherwise, it will result in an error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rpeshkov |
Solution 2 | |
Solution 3 | Daniel Danielecki |
Solution 4 | Chamila Maddumage |