Can I submit an object to a reactive form?

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

This is my form:

this.parameterForm = this.fb.group({

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

      

The third attribute (parameterType) must be an object. (The name and description are just simple strings.

My HTML for parameterType (formControlName is used to display 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 element are objects (which are created elsewhere). When submitting the form, I would like to have a parameterType object. The view is trying to parse the form for an object named Parameter:

export class Parameter {

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

  public parameterType? : ParameterType
} 

      

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

My submit function is like this:

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

      

Now I just do it so that in the parameterType im send the id and through the service I get the object, but this solution is not very nice. Do you know that I could pass an object to a form?

thank

+3


source to share


2 answers


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



+6


source


You have several options:

Let's say I have the following view:

user: FormGroup;

this.user = this.formBuilder.group({
  account: this.formBuilder.group({
    email: ['', [Validators.required, Validators.pattern(EmailRegex)]],
    password: ['', Validators.required],
    passwordConfirm: ['', Validators.required]
  }, { validator: this.matchingPasswords('password', 'passwordConfirm') })
});

      

From there, you can set the values ​​of your form with Object

:

let user: SignUp = {
  account: {
    email: this.mail,
    password: '',
    passwordConfirm: ''
  }
};
this.user.setValue(user);

      

Where Signup

is the interface:



export interface SignUp {
  account: {
    email: string;
    password: string;
    passwordConfirm: string;
  }
}

      

You can create a new one Object

from the form:

let jsonResult = {
  email: this.user.value.account.email,
  password: this.user.value.account.password
};

      

or use the form as an object from the interface (for example @Output

):

@Output() randomOutput= new EventEmitter<SignUp>();

let data: SignUp = Object.assign({}, this.user.value);

this.randomOutput.emit(data);

      

+2


source







All Articles