我想创建一个表单并为其控件使用新的自定义组件。所以我创建了一个新组件并将其包含在父表单中。但是虽然父表单有一个formGroup,但Angular抱怨说它没有。
错误:
错误:formControlName必须与父formGroup指令一起使用。 您将要添加formGroup 指令并将其传递给现有的FormGroup实例(您可以在类中创建一个)。
父表格有:
<form [formGroup]="learningObjectForm" (ngSubmit)="onSubmit()" novalidate>
<div>
<button type="submit"
[disabled]="learningObjectForm.pristine">Save</button>
</div>
<ava-form-control [label]="'Resource'"></ava-form-control>
</form>
在.ts:
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.learningObjectForm = this.fb.group({
text: '',
});
}
在自定义组件中我有
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'ava-form-control',
template: ` <div>
<label>{{label}} :</label>
<input formControlName="{{name}}">
</div>
`
})
export class FormControlComponent implements OnInit {
@Input() label: string;
@Input() name: string;
constructor() {}
ngOnInit() {
if (this.name === undefined) {
// turns 'The Label' into 'theLabel'
this.name = this.label[0].toLowerCase().concat(this.label.slice(1));
this.name = this.name.split(' ').join('');
console.log(this.label, this.name);
}
}
}
答案 0 :(得分:2)
您还应该将formGroup
个实例与control name
一起传递到custom component
。然后在自定义组件中的form control
下创建formGroup
。您的自定义组件将在您提供的同一formGroup下虚拟创建控件。
<form [formGroup]="learningObjectForm" (ngSubmit)="onSubmit()" novalidate>
<div>
<button type="submit"
[disabled]="learningObjectForm.pristine">Save</button>
</div>
<ava-form-control [label]="'Resource'" [formGroup]="learningObjectForm" [controlName]="'mycontrol'"></ava-form-control>
</form>
custom.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'ava-form-control',
template: ` <div>
<label>{{label}} :</label>
<input [formControl]="formGroup.controls[controlName]>
</div>
`
})
export class FormControlComponent implements OnInit {
@Input() label: string;
@Input() formGroup: FormGroup;
@Input() controlName: string;
constructor() {}
ngOnInit() {
let control: FormControl = new FormControl('', Validators.required);
this.formGroup.addControl(this.controlName, control);
}
}
使用此功能,您的父组件可以访问其各自自定义组件中定义的所有表单控件。
答案 1 :(得分:0)
我玩了很长时间,一直没有运气。
实现ControlValueAccessor接口的结果更好,如下所示: https://alligator.io/angular/custom-form-control/
这实际上很简单,我也安装了Example StackBlitz