首页 > 代码库 > [Angular2 Form] Nested formGroup, and usage of formGroupName
[Angular2 Form] Nested formGroup, and usage of formGroupName
We can nest formGorup:
this.reactiveForm = fb.group({ username: [ ‘‘, [ Validators.required, Validators.minLength(3) ] ], pwds: fb.group({ pwd: ‘‘, rpwd: ‘‘ }, {validator: passwordValidator}) });
We make password as an own group. So in html, we need to use formGroupName istead of formControlName.
<form [formGroup]="reactiveForm" novalidate autocomplete="off"> <div class="form-field"> <label>Username:</label> <input formControlName="username"> <div class="field-error-message" *ngIf="reactiveForm.controls.title.errors?.required"> Username is required </div> </div> <div formGroupName="pwds"> <div class="form-field"> <label>pwd</label> <input formControlName="pwd"> </div> <div class="form-field"> <label>rpwd</label> <input formControlName="rpwd"> </div> </div></form>
And how we check the value or errors?:
<pre> {{reactiveForm.get(‘pwds‘)?.value | json}} {{reactiveForm.get(‘pwds‘)?.errors | json}}</pre>
And we also passwordValidator haven‘t cover yet, it is just a fucntion:
function passwordValidator(c: AbstractControl){ return c.get(‘pwd‘).value =http://www.mamicode.com/== c.get(‘rpwd‘).value ? null : // valid { //invalid nomatch: true }}
And notice that we put this validator inside the nested group, so we can get nice error effect:
[Angular2 Form] Nested formGroup, and usage of formGroupName
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。