Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 719
Abx Avatar asked Aug 02 '18 09:08

Abx


People also ask

Can assign to because it is a read only property?

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.

Can not assign to read only 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 .


2 Answers

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.

like image 200
rpeshkov Avatar answered Sep 30 '22 03:09

rpeshkov


That is not the way to set value. Correct way to set is using setValue() or patchValue()

this.myControl.setValue('contact');
like image 27
Amit Chigadani Avatar answered Sep 30 '22 04:09

Amit Chigadani