Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i send a object to a reactive form?

I would like to ask if it is possible to send a whole object to the reactive form in angular 2.

This is my form:

this.parameterForm = this.fb.group({

  'name': ['', Validators.required],
  'description': "",
  'parameterType':''
});

The third attribute (parameterType) should be a object. (The name and description are only plain strings.

My HTML for the parameterType is(formControlName is used to map it):

<label for="parameterType">Parameter Type</label>
<select id="parameterType" class="form-control" formControlName="parameterType">
  <option *ngFor="let parameterType of parameterTypes" [value]="parameterType">
    {{parameterType.name}}
  </option>

</select>

The values in the select are objects (which are created elsewhere). When submitting the form, I would like to have the parameterType object. The submit is trying to parse the form to a object called Parameter:

export class Parameter {

  public id: number;
  public name: string;
  public description: string;

  public parameterType? : ParameterType
} 

But when im trying to read the result in the console, the parameterType contains just a string "[Object object]", which looks like the parameterType is just a String and when submitting the form, the object is converted to a simple string.

My submit function is like this:

  onSubmit( {parameter}:{parameter: Parameter} ) {
    console.log(parameter);
  }

Now im just doing it so, that into parameterType im sending the id and through a service I get the object but this solution is not very nice. Do you know any way i could pass the object to the form?

Thanks

like image 871
arfis Avatar asked Dec 07 '22 18:12

arfis


1 Answers

I think you need to use [ngValue] instead of [value].

like image 140
Amit Avatar answered Dec 10 '22 12:12

Amit