![](/img/trans.png)
[英]How do I get reference to the FormControl from a component that implements ControlValueAccessor?
[英]ControlValueAccessor with multiple formControl in child component
我在子组件中有多个formcontrol,如何在子组件中应用验证器,所以原始表单将无效。 最好使用ControlValueAccessor来实现它,但要从简单的@input表单组开始。
@Component({
selector: 'my-child',
template: `
<h1>Child</h1>
<div [formGroup]="childForm">
<input formControlName="firstName">
<input formControlName="lastName">
</div>
`
})
export class Child {
@Input()
childForm: FormGroup;
}
我不知道为什么这个问题被否决,但是我认为这可能对其他人有帮助,所以我发布了答案。 在多次尝试绑定孩子的表单组后,我能够成功绑定值
@Component({
selector: 'my-child',
template: `
<h1>Child</h1>
<div [formGroup]="name">
<input formControlName="firstName">
<input formControlName="lastName">
</div>
`,
providers: [
{provide: NG_VALUE_ACCESSOR, useExisting: Child, multi: true}
]
})
export class Child implements ControlValueAccessor {
name: FormGroup;
constructor(fb: FormBuilder) {
this.name = fb.group({
firstName:[''],
lastName: ['']
});
}
writeValue(value: any) {
if(value) {
this.name.setValue(value);
}
}
registerOnChange(fn: (value: any) => void) {
this.name.valueChanges.subscribe(fn);
}
registerOnTouched() {}
}
起初,这对我有很大帮助,但后来我发现,我们使事情变得过于复杂。 我们不必构建自己的formControl,只需将formGroup传递给子组件即可。 在父组件中,而不是
this.form = fb.group({
name:['Angular2 (Release Candidate!)'],
username: [{firstName: 'First', lastName: 'Last'}],
email:['My Email']
});
我们将用户名初始化为FormGroup而不是控件:
this.form = fb.group({
name:['Angular2 (Release Candidate!)'],
username: fb.group({
firstName: ['First'],
lastName: ['Last']
}),
email:['My Email']
});
在子组件中,我们需要FormGroup的Input属性
@Input()
usernameGroup: FormGroup;
在子模板中:
<div [formGroup]="usernameGroup">
<input formControlName="firstName">
<input formControlName="lastName">
</div>
然后在父模板中:
<my-child [usernameGroup]="form.controls.username"></my-child>
有关更多信息,请查看这篇文章: https : //scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2
在这里构建自己的formControl实在是一个矫kill过正,有关此的更多信息,请在这里查看: http : //blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2 .html
无需实现ControlValueAccessor,可以轻松实现您想做的事情。 相反,您可以简单地在子组件中设置viewProviders,以使用现有的父NgForm作为ControlContainer。
然后,无需将form / formGroup作为输入参数传递给子组件,因为表单控件将自动成为父表单的一部分。
child.component.ts:
@Component({
selector: 'child',
templateUrl: './child.component.html',
viewProviders: [{ provide: ControlContainer, useExisting: NgForm}]
})
export class Child {
@Input() firstName;
@Input() lastName;
}
input-child.component.html:
<h1>Child</h1>
<div>
<input [(ngModel)]="firstName" name="firstname">
<input [(ngModel)]="lastName" name="lastname">
</div>
parent.component.html:
<form #personalForm="ngForm" name="personalForm">
<child [firstName]="firstName" [lastName]="lastName"></child>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.