Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormControl display value

How to display some text in input FormControl that not equal to value of this FormControl?

For example, get some object from a server - {id: 1, name: "Name1"}, and set value of FormControl to that object or to object.id but display value set to object.name - "Name1".

Why i need it:

I use angular material autocomplete and it set the value of FormControl to object (from selected mat-option) and display value to string via displayWith. I want to repeate this behavior when fetch data from server for some consistency and convenience

like image 283
alarcl Avatar asked Dec 30 '18 15:12

alarcl


1 Answers

I do some research for my question.

It is need to use FormControlDirective and its valueAccessor.writeValue() for set display value of input (it use renderer) or as alternative nativeElement.value.

And FormControl's setValue() with emitModelToViewChange = false for set FormControl value.

In template

<input [formControl]="ctrlF" #ctrlD="ngForm">

In controller

 @ViewChild('ctrlD', {read: FormControlDirective})
 ctrlD :FormControlDirective
 ...
 this.ctrlD.valueAccessor.writeValue("display value")
 this.ctrlD.control.setValue({foo: "foo", bar: "bar"}, {
     emitModelToViewChange: false
 })

planker

like image 100
alarcl Avatar answered Oct 17 '22 22:10

alarcl