user1275105
user1275105

Reputation: 2753

How to pass value that's being fetched asynchronously to a component's Input in Angular2

I am trying to pass a value to a component's input

<my-comp [question]="currentQuestion"></my-comp>

but the variable currentQuestion is being fetched asynchronously at the point the page first loads so understandably I get an undefined error. How can I get around this?

template of my-comp

<div>
  <p>{{question.title}}</p>
</div>

class of my-comp

@Component({
  selector: "my-comp",
  templateUrl: "./my-comp.html"
})
export class MyComp {
  @Input() question: any;

  constructor() {}
}

Upvotes: 1

Views: 25

Answers (1)

Andrei Zhytkevich
Andrei Zhytkevich

Reputation: 8099

Try Elvis operator ?. inside interpolation in your child component my-comp.

{{ currentQuestion?.aField }}

In case currentQuestion is falsy (undefined, null, etc.) it won't access aField member.

currentQuestion will be undefined until you get response from asynchronous call.

Update:

Your my-comp template should look like this:

<div>
  <p>{{question?.title}}</p>
</div>

It has ?. operator inside interpolation.

Upvotes: 1

Related Questions