Home > Net >  In an input text how to set value with an object and display a field of the object?
In an input text how to set value with an object and display a field of the object?

Time:10-02

I use form reactive and I get an object:

{
 id: 47,
 codice: "Milano"
}

that send me the server.

When I assign it to the input text it display [object Object].

How to display "Codice" field in the input but mantain the value with the object? Because when I submitting the form I retrive values with

this.editForm.get('destZona').value

and I need both information: id and codice.

If you want can I share with StackBlitz an example. Thanks!

CodePudding user response:

Input text will display and return text, you cannot put objects in it.

You should have a child form group for the destZona object.

this.editForm = this.formBuilder.group({
    destZona: this.formBuilder.group({
        id: [yourObjId],
        codice: [yourObjCodice]
    })
});

Then you can refer to it in your template with a formGroupName="destZona" on one of your input parent, and put formControlName="codice" on the input.

CodePudding user response:

Create formGroup variable

myForm: FormGroup;

create a method that will take object and turn it into FormGroup

createFormGroup(obj): FormGroup {
    return new FormGroup({
      id: new FormControl(obj.id),
      codice: new FormControl(obj.codice),
    });
  }

While subscribing to service use RxjS map to generate FormGroup and assign to myForm variable

  constructor(private dataService: DataService) {
    dataService
      .getData()
      .pipe(
        map((data) => (this.myForm = this.createFormGroup(data)))
      )
      .subscribe();
  }

In template:

<form [formGroup]="myForm">
  <input type="text" formControlName="codice" />
</form>

Angular demo

  • Related