Cannot assign to 'value' because it is a constant or a read-only property. Angular 6
Asked Answered
D

4

18

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?

Dished answered 2/8, 2018 at 9:1 Comment(0)
A
17

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.

Alyce answered 2/8, 2018 at 9:5 Comment(2)
Thanks ..Its fine now.Dished
@rpershkov Can you help me on something, because I am trying the same thing and I tried to use patchValue or setValue but it doesn't change the value of the formGroup. If you can we can we can discuss in a chat.Newlywed
V
15

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

this.myControl.setValue('contact');
Viridescent answered 2/8, 2018 at 9:4 Comment(7)
He has no form.Brolly
And it should be a comment.Brolly
@trichetriche Why comment? Can you please remove the downvote?Viridescent
Because you are giving a one liner to a person that didn't read the documentation. If you want me to remove my downvote, you're going to edit your answer to link the documentation and cover patchValue, then I'll give you an upvote.Brolly
I have edited it, but patchValue and setValue are almost same w.r.t to form ControlsViridescent
Agreed, but you did gave both documentation, so it's fine by me !Brolly
Thanks :) short & straight forward answer.Convention
A
0

In terms of contact form to make it invalid manually this one worked for me this.contactForm.setErrors({ valid: false });

Allan answered 5/3, 2020 at 11:55 Comment(0)
I
0

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.
Inconclusive answered 22/4, 2022 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.