【发布时间】:2020-06-27 19:21:03
【问题描述】:
在这里转圈,这里的所有文章和问题都建议在 Angular 9 项目中为表单数组引用模板中的控件属性。
但是我得到一个错误,说控件属性不存在。我所有的数据都被拉到表单中,这就是抛出我的编译错误。
模板
<form name="mainForm" [formGroup]="mainForm">
<div formArrayName="phoneNumbers" *ngFor="let item of mainForm.get('phoneNumbers').controls; let i = index">
<div [formGroupName]="i">
<input formControlName="label" />
<input formControlName="number" />
</div>
</div>
</form>
组件
import { Person } from "@shared/models/person.model";
import { DataService } from "../services/people-data-service";
import {
Component,
OnInit,
ViewEncapsulation,
ChangeDetectionStrategy,
Inject
} from "@angular/core";
import { FormBuilder, FormGroup, FormArray, FormControl } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { fuseAnimations } from "@fuse/animations";
@Component({
selector: "fw-person",
templateUrl: "./person.component.html",
styleUrls: ["./person.component.scss"],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PersonComponent implements OnInit{
id: string;
entity: Person;
pageType: string;
mainForm: FormGroup;
constructor(
@Inject("PeopleService")
private _dataService: DataService<Person>,
private _activatedRoute: ActivatedRoute,
private _formBuilder: FormBuilder,
) {
this.entity = new Person();
}
ngOnInit(): void {
this.id = this._activatedRoute.snapshot.params["id"];
if (this.id !== "new") {
this._dataService.getByKey(this.id).subscribe(entity => {
this.entity = new Person(entity);
this.updateFormFields(entity);
this.pageType = "edit";
});
} else {
this.pageType = "new";
this.entity = new Person();
}
this.mainForm = this.createPersonForm();
}
createPersonForm(): FormGroup {
return this._formBuilder.group({
firstName: [this.entity.firstName],
familyName: [this.entity.familyName],
phoneNumbers: this._formBuilder.array([]),
});
}
updateFormFields(entity): void {
Object.keys(this.mainForm.controls).forEach(key => {
this.mainForm.controls[key].patchValue(entity[key]);
});
}
get phoneNumbers() {
return this.mainForm.get('phoneNumbers') as FormArray;
}
}
人物模型
export class Person{
firstName: string;
familyName: string;
phoneNumbers: [{
label: string,
number: string
}];
constructor(person?) {
{
this.firstName = person.firstName || '';
this.familyName = person.familyName || '';
this.fullName = person.firstName + ' ' + person.familyName || '';
this.phoneNumbers = person.phoneNumbers || [{label:'Work', number:'123'}];
}
}
}
【问题讨论】:
-
你能在 stackblitz 上发布你的代码吗?
-
@bjdose stackblitz.com/edit/angular-mc7s3t 有趣的是,我没有收到编译错误,但我也无法访问我的 *ngFor 中的任何数据
-
您无法访问 *ngFor 中的任何数据,因为该数组已初始化为空数组。
-
当然 - 谢谢。并没有真正解释为什么它在我的实际项目中不起作用。但我有一个可以使用的工作版本 - 非常感谢您的帮助
-
我在一个真实的项目中编写了代码,我看到了这个问题,我在这里找到了一些解决方案:github.com/angular/angular-cli/issues/6099 和另一个更易于阅读的解决方案:stackoverflow.com/questions/46926182/…
标签: angular angular-reactive-forms