typescript - Angular 动态表单可观察输入属性总是为 null
我正在自学 Angular 的响应式表单,并且在跟随动态表单指南时遇到了困难。
在 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 输入属性的值似乎总是为 null。
错误 TypeError: 无法读取 null 的属性 'forEach' 在 QuestionControlService.toFormGroup (question-control.service.ts:19) 在 DynamicFormComponent.ngOnInit (dynamic-form.component.ts:22)
移除 .pipe(delay(10)) 会使示例恢复到正常工作状态。
有人能解释一下为什么 questions 输入属性为空吗?
请查看 StackBlitz 以获取工作示例。
答案#1
你收到错误是因为输入属性绑定是异步发生的。
试试这个:
<div>
<ng-container *ngIf="questions$ | async as questions">
<app-dynamic-form [questions]="questions"></app-dynamic-form>
</ng-container>
</div>
