【发布时间】:2020-09-01 20:17:31
【问题描述】:
大家好,我正在尝试构建一个具有 formArray 的直通表单,并且我希望能够动态添加或删除输入字段,但我得到了错误: 找不到具有未指定名称属性的控件
这是我的代码:
ts 文件:
@Component({
selector: 'app-create-ilm-policy',
templateUrl: './create-ilm-policy.component.html',
styleUrls: ['./create-ilm-policy.component.scss']
})
export class CreateIlmPolicyComponent implements OnInit {
mainForm:FormGroup
constructor(){}
get patterns(){
return <FormArray>this.mainForm.get('indexPatterns')
}
ngOnInit(): void {
this.mainForm = new FormGroup({
indexPatterns: new FormArray([this.addIndexPattern()]),
rolloverAlias: new FormControl()
})
}
addIndexPattern(): FormControl{
return new FormControl()
}
removeIndexPatternRow(index: number) {
(<FormArray>this.mainForm.get('indexPatterns')).removeAt(index)
}
addIndexPatternRow(){
(<FormArray>this.mainForm.get('indexPatterns')).push(this.addIndexPattern())
}
}
html 文件:
<form [formGroup]="mainForm">
<div formArrayName="indexPatterns" *ngFor="let pattern of patterns.controls; index as i">
<div class="d-flex align-items-center" [formControl]="i">
<mat-form-field appearance="fill">
<mat-label>modèle d'indices</mat-label>
<input matInput [formControl]="patterns.controls[i]"> <!--line that throws the error!!!!!!!-->
<mat-hint>ajouter * à la fin</mat-hint>
</mat-form-field>
<mat-icon class="pointer" color="warn" (click)="removeIndexPatternRow(i)" svgIcon="delete_forever" aria-hidden="false"></mat-icon>
</div>
</div>
</form>
【问题讨论】:
-
IMK,当我们有
[formGroup]时,我们传递[formControlName]而不是实际控件,我们让 angular 选择控件本身。