2
votes

I'm using Angular Material for creating a form. For some fields the user should get a autocomplete function. Those fields should be also populated from the backend, if the user provides a serial number.

My question is, how can I set the text of a textbox which is linked to a autocomplete via code?

I copied a StackBlitz and modified it to match my scenario: https://stackblitz.com/edit/angular-material-autocomplete-async1-jxrahv?file=src%2Fapp%2Fapp.component.ts

If you click on the "click me!" Button, I want the text of the textbox to change to "Windstorm" (which doesn't happen).

Thanks!

1
well your actual form control value is an object and you are trying to set the value with a string, so it won't work. If you enter it as an object, it will work: stackblitz.com/edit/…AJT82
@AJT_82 is right. Once you added [matAutocomplete]="auto" to input MatAutocompleteTrigger value accessor starts handling all forms events. And MatAutocompleteTrigger uses displayWith method to write in input value. github.com/angular/material2/blob/…yurzui
Being agains the rules and totally off-topic: Very nice to see you again @yurzui Long time no see. All good I hope! :)AJT82
@AJT_82 Yes, all goes well, thanks. Have you decided to remember the angular forms?)yurzui
@yurzui Haha :D Yeah! My newest passion is ionic though. Work has gotten me into learning and developing with ionic, and I love it! :)AJT82

1 Answers

1
votes

You are feeding your autocomplete with array of objects, so when you are trying to set the value with "just" a string:

this.usersForm.get('userInput').setValue("Windstorm");

... it will not work. Set the whole object as value, and you're good! :)

this.usersForm.get('userInput').setValue({ id: 1, name: 'Windstorm' });

Modified StackBlitz