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?
The error "Cannot assign to 'X' because it is a read-only property" occurs when we try to change the value of a read-only property in a class or an object. To solve the error, remove the readonly modifier or use a type assertion to change the value of the property.
The error "Cannot assign to read only property of object" occurs when we try to change a property of an object that has been frozen or when a property has been defined with Object. defineProperties() . To solve the error, create a copy of the object or array, or set the property to writable .
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.
That is not the way to set value. Correct way to set is using setValue() or patchValue()
this.myControl.setValue('contact');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With