我有一个自定义HTML模板,该模板正在Angular反应形式中使用,当我尝试在element标签中声明formControlName
时,此模板会产生错误。我收到的错误是
Cannot find control with unspecified name attribute
但是,我要声明控件名称,如下面的代码所示。如果我用常规的input
替换了自定义HTML模板,并在input元素上声明了formControlName
,则表单可以按预期工作。
这是我的表格
<div class="row mt-xl">
<div class="col-12">
<form [formGroup]="ipRangeForm">
<div formArrayName="ipRanges">
<div *ngFor="let ranges of ipRangeForms.controls; let i=index" [formGroupName]="i">
<!-- core-text-input produces the error -->
<core-text-input [form]="ipRangeForm" [key]="'startingRange'" formControlName="'startingRange'"></core-text-input>
<!-- This regular input element works properly with the formControlName attribute -->
<mat-form-field style="width: 100%;">
<label>
<input matInput placeholder="Starting Range" value="" formControlName="startingRange">
</label>
</mat-form-field>
</div>
</div>
</form>
</div>
</div>
起初,我认为问题在于如何在组件文件中声明我的反应形式,但是,如果是这种情况,则该形式不适用于常规输入元素,但确实如此。因此,问题本身不可能是表格本身。这使我认为custom元素一定有问题。似乎自定义元素没有像常规输入元素那样使用和使用formControlName属性。
核心文本输入模板
<div class="form-input">
<mat-form-field>
<input matInput [placeholder]="getTranslateKey(key + '.label') | translate" [formControl]="control" formControlName="{{formControlName}}">
</mat-form-field>
</div>
核心文本输入组件
@Component({
selector: 'core-text-input',
templateUrl: './text-input.component.html',
styleUrls: ['./text-input.component.scss']
})
export class TextInputComponent extends AbstractInputComponent {
constructor( baseService: BaseService ) {
super( baseService );
}
}
AbstractInputComponent组件
export abstract class AbstractInputComponent extends AbstractBaseComponent implements OnInit {
@Input() form: FormGroup;
@Input() key: string;
@Input() formControlName: string;
control: AbstractControl;
constructor( baseService: BaseService ) {
super( baseService );
}
ngOnInit() {
this.control = this.form.controls[this.key];
console.log('formControlName: ' + this.formControlName);
}
}
活动表单组件(在其中声明了表单的模型)
export class ReactiveFormComponent extends AbstractPageComponent implements OnInit, OnDestroy {
ipRestrictionEnabled: boolean;
ipRangeForm: FormGroup;
constructor(pageService: PageService, private formBuilder: FormBuilder) {
super(pageService);
}
ngOnInit() {
this.ipRestrictionEnabled = false;
this.ipRangeForm = this.formBuilder.group(
{
ipRanges: this.formBuilder.array([])
}
);
}
get ipRangeForms() {
return this.ipRangeForm.get('ipRanges') as FormArray;
}
addRange() {
const ipRange = this.formBuilder.group({
startingRange: ['']
});
this.ipRangeForms.push(ipRange);
}
deleteRange(index) {
this.ipRangeForms.removeAt(index);
}
}
我在这里遗漏了什么导致自定义输入元素中的错误?