Angular dynamic form observable input property always null

Viewed 243

I'm teaching myself reactive forms in Angular and have become stuck following the Dynamic Forms guide.

In the question.service.ts file, I've added a delay to the returned observable to simulate a HTTP request:

return of(questions.sort((a, b) => a.order - b.order)).pipe(delay(10));

This observable is passed to the app-dynamic-form component in the app-root template:

<app-dynamic-form [questions]="questions$ | async"></app-dynamic-form>

But the questions input property value seems to be always null.

ERROR TypeError: Cannot read property 'forEach' of null at QuestionControlService.toFormGroup (question-control.service.ts:19) at DynamicFormComponent.ngOnInit (dynamic-form.component.ts:22)

Removing the .pipe(delay(10)) returns the example to a working state.

Can anyone explain why questions input property is null?

See StackBlitz for working example.

1 Answers

You are getting error because input property binding is happening asynchronusly.

Try this:

    <div>
        <ng-container *ngIf="questions$ | async as questions">
         <app-dynamic-form [questions]="questions"></app-dynamic-form>
        </ng-container>
    </div>
Related