我想使用来自 ng-template 的角反应形式的某些部分。分离在不同的组件中可以很好地使用 ngViewProviders。但我想通过 ng-template 来实现它。
<h1>Test Reactive Form</h1>
<form [formGroup]="form">
<ng-container
[ngTemplateOutlet]="formArray"
[ngTemplateOutletContext]="{formGroup:form, arrayName:test}"
></ng-container>
</form>
{{form.value | json}}
<ng-template #formArray let-formGroup="formGroup" let-arrayName="arrayName" >
<ng-container [formGroup]="formGroup">
<div formArray="arrayName">
<ng-container *ngFor="let t of arrayName.controls;let i = index;" [formGroupName]="i">
{{formGroup.value | json}}
<input type="text"/>
</ng-container>
</div>
</ng-container>
</ng-template>
`,
})
export class App {
name = 'Angular';
form;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
test: this.fb.array([]),
});
const test = this.fb.group({
name: 'Test name',
});
this.test.push(test);
const test_1 = this.fb.group({
name: 'test name 2',
});
this.test.push(test_1);
}
get test(): FormArray {
return this.form.get('test') as FormArray;
}
出现类似错误 错误 错误:找不到名称为“0”的控件
Stackbitz 链接:https://stackblitz.com/edit/angular-9jmcfq?file=src%2Fmain.ts
属性
formGroupName
、formGroup
、formArray
和 formArrayName
必须定义正确的 HTML 元素。
<ng-container *ngFor="let t of arrayName.controls;let i = index;"
[formGroupName]="i">
{{formGroup.value | json}}
<input type="text"/>
</ng-container>
<div *ngFor="let t of arrayName.controls;let i = index;"
[formGroupName]="i">
{{formGroup.value | json}}
<input type="text"/>
</div>