15

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?

Abx
  • 2,572
  • 3
  • 25
  • 47

3 Answers3

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.

rpeshkov
  • 4,355
  • 2
  • 25
  • 41
  • Thanks ..Its fine now. – Abx Aug 02 '18 at 09:10
  • @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. – Abedin.Zhuniqi Apr 02 '19 at 12:29
10

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

this.myControl.setValue('contact');
Amit Chigadani
  • 22,665
  • 10
  • 67
  • 83
0

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

Daniel Danielecki
  • 3,527
  • 3
  • 29
  • 41