Angular2 Update FormGroup nested value?

时间秒杀一切 提交于 2020-07-17 04:09:17

问题


I have this inside a component:

private formBuilder: FormBuilder

...

signupForm: FormGroup;

...

this.signupForm = this.formBuilder.group({
  'name':             [null, Validators.required],
  'account':          this.formBuilder.group({
    'email':          [null, [Validators.required, ...]],
    'confirm_email':  [null, Validators.required],
  }, {validator: ValidationService.emailMatcher}),
  'password':         [null, [Validators.required,...]]
});

And I want to set the value for the email field. I tried this, but no luck:

this.signupForm.patchValue({'email': 'myvalue@asd.com'});

But the value is nested, so whats the sintax in this case? I also tried:

this.signupForm.patchValue({'account.email': 'myvalue@asd.com'});

Also searched here:

https://angular.io/docs/ts/latest/api/forms/index/FormGroup-class.html#!#patchValue-anchor

Thanks


回答1:


Try this:

this.signupForm.patchValue({account:{email: 'myvalue@asd.com'}});

Another solution is:

(<FormGroup>this.signupForm.controls['account']).controls['email'].patchValue('myvalue@asd.com');

Sorry for bad indentation.



来源:https://stackoverflow.com/questions/41872990/angular2-update-formgroup-nested-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!