2

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 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Can you tell me about this: Before adding .pipe(delay(10)) there is no delay but questions$ was always an observable because of using of. So why can't async pipe manage it without using *ngIf when it is delayed?
Thanks this absolutely solves it. I've not added the container however as it seems you can do it inline: <app-dynamic-form *ngIf="questions$ | async as questions" [questions]="questions"></app-dynamic-form>
async pipe allows the subscription to observables inside of the angular template syntax. Before async resolve the data the component get created in the dom, that's why adding delay to it causing error. @Ramesh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.