physicsboy
physicsboy

Reputation: 6316

Can't bind to property of child component as variable hasn't loaded?

I have a component with a child, and I am wanting to pass a variable to the child, but the variable takes a second or two to load properly from a subscribe.

I have given an *ngIf but I still get the error:

Can't bind to 'event' since it isn't a known property of 'app-race-card'.

Is this because of the time it takes to actually load the event from the subscribe or am I missing something bigger?

I figured that putting an *ngIf="event" in the element call for the <app-race-card> call would mean that it would wait until event was populated before attempting to load the component, and then actually pass what was now present?

event.component.ts

let event;

ngOnInit() {
   this.subscribeService();
}

subscribeService() {
    this.service.eventSubject
    .subscribe(res => this.event = res);
  }

event.component.html

<comp *ngIf="event" [event]="event"></comp>

comp.component.ts

export class Component implements OnInit {

  @Input() event: IEvent;

  constructor() {
  }

  ngOnInit() {
  }

}

Upvotes: 1

Views: 155

Answers (2)

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Most likelly (you don't show what this.eventService.eventSubject is actually doing), you are confused about how Change Detection runs. Your eventSubject(as name suggests) probably reacts to some mouse or keyboard event. Or maybe an Ajax request, XHR or even something else. All these mechanisms triggers Change Detection to run. When Change Detection is triggered it checks if properties of the class have changed, if so - it updates the view.

Now in your case when component loads, callback .subscribe(res => this.event = res); haven't yet accrued, so this.event is still undefined. But if you conditionally state in template *ngIf="event" Angular will ignore that field in template and will not throw any errors. And when .subscribe(res => this.event = res); is executed and then causes a Change Detection to be triggered, it checks all properties (including this.event) if they have changed. And because this.event was undefined before and now has some value, it rerenders the view, but this time *ngIf="event" will return true so the value will be displayed.

p.s. your solution is good. No need to worry. If you have heard about the ? (Elvis operator), it serves the exact same reason - to check if value is defined.

Upvotes: 2

hjbello
hjbello

Reputation: 651

I think that it is possible that your variable event is not an instance of IEvent. Or that perhaps it is is not accessible to your child component. Try defining

event: Ievent;

in your parent event.component.ts. Instead of

let event;

Upvotes: 0

Related Questions