我正在自学 Angular 中的响应式(Reactive)形式,并且陷入了遵循 Dynamic Forms guide 的困境。 .
在 question.service.ts
文件中,我向返回的可观察量添加了延迟以模拟 HTTP 请求:
return of(questions.sort((a, b) => a.order - b.order)).pipe(delay(10));
此可观察量被传递到 app-root
模板中的 app-dynamic-form
组件:
<app-dynamic-form [questions]="questions$ | async"></app-dynamic-form>
但是questions
输入属性值似乎始终为空。
ERROR TypeError: Cannot read property 'forEach' of null at QuestionControlService.toFormGroup (question-control.service.ts:19) at DynamicFormComponent.ngOnInit (dynamic-form.component.ts:22)
删除 .pipe(delay(10))
会使示例恢复到工作状态。
任何人都可以解释为什么questions
输入属性为空吗?
参见StackBlitz用于工作示例。
最佳答案
您收到错误,因为输入属性绑定(bind)是异步发生的。
试试这个:
<div>
<ng-container *ngIf="questions$ | async as questions">
<app-dynamic-form [questions]="questions"></app-dynamic-form>
</ng-container>
</div>
关于 Angular 动态形式可观察输入属性始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61030611/