我正在尝试在 formarray 中的 formcontrol 上实现 Material 自动更正,但是当我尝试访问 ts 文件中的 formcontrol 时,它无法访问它。谁能帮帮我吗。
html文件:
<div formArrayName="applicants">
<div *ngFor="let applicant of appForm.controls.applicants.controls; let i=index; let last = last">
<div [formGroupName]="i">
<div class="row">
<label for="applicant_short_name" class="col-sm-3 form-control-label">Applicant {{i+1}}</label>
<div class="col-sm-7">
<div class="form-group">
<!-- <input type="text" formControlName="applicant_short_name" class="form-control" id="inputFirstName" placeholder="Applicant"> -->
<!-- <mat-form-field > -->
<input type="text" class="form-control" id="inputFirstName" placeholder="Applicant" [matAutocomplete]="auto" [formControlName]="applicant_short_name">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let state of filteredNames | async | slice:0:3" [value]="name">
<span>{{ name }}</span>
</mat-option>
</mat-autocomplete>
<!-- </mat-form-field> -->
</div>
</div>
.ts 文件:
this.appForm.controls.applicants.controls[0].controls.applicant_short_name.valueChanges.subscribe(val => {
this.filterNames(val);
});
其中 appform 是我的表单组
申请人是formarray
申请人的简称是formcontrol。
截至目前,controls[0] 正在抛出错误,即 AbstractControl 上不存在控件。
任何人都可以在这里帮助我吗?
提前致谢!
最佳答案
您需要将对象类型定义为具体的类,而不仅仅是依赖于接口(interface)。我假设 appForm
定义为 FormGroup
或 FormArray
在你的代码中的某个地方(你应该显示所有相关的代码)。但是controls
两个类的成员返回 AbstractControl[]
和 AbstractControl
界面没有controls
成员 - 它仅在 FormGroup
中的类级别定义和 FormArray
.因此,假设您使用的是 FormGroup
s,你需要投:
const outerGroup: FormGroup = this.appForm.controls.applicants as FormGroup;
const innerGroup: FormGroup = outerGroup.controls[0] as FormGroup;
innerGroup.controls.applicant_short_name.valueChanges.subscribe(val => {
this.filterNames(val);
});
您也可以将语句内联转换,但这会变得非常困惑。
关于angular - 在 FormArray 中访问 FormGroup 中的 FormControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579782/