3

Using Angularfire2, I'm trying to pass an object retrieved from the Firebase db from parent to child:

Parent:

@Component({
  selector: 'app-page',
  styleUrls: ['./page.component.scss'],
  template: `
    <app-page-render [page]="page"></app-page-render>
  `,
})
export class PageComponent implements OnInit {
  slug: string;
  page: FirebaseObjectObservable<Page>;

  constructor(private af: AngularFire, private route: ActivatedRoute) {
  }

  ngOnInit() {
    this.route.params
      .switchMap((params: any) => this.af.database.object(`/pages/${params['page-slug']}`))
      .subscribe(page => this.page = page);
  }

}

Child:

@Component({
  selector: 'app-page-render',
  styleUrls: ['./page-render.component.scss'],
  template: `
   <div class="page-header">
      <div class="page-banner">
        <picture>
          <source [srcset]="page.header.desktop" media="(min-width: 1024)">
          <source [srcset]="page.header.tablet" media="(min-width: 768px)">
          <img [src]="page.header.mobile" [alt]="page.header.alt" class="page-banner--image">
        </picture>
        <h1 class="page-banner--heading">{{page.header.title}}</h1>
      <div>
    </div>
    <main class="main-container">
      <div [innerHTML]="page.content"></div>
    </main>
  `
})
export class PageRenderComponent implements OnInit {
  @Input()
  page: any;

  constructor() { }

  ngOnInit() {
  }

}

Of course this gives me "header is undefined" because the child is resolving the data before it renders. I could add (page | async)? to all the variables but that means there are a bunch of async calls in the one template which I understand isn't very good practice.

Any best practice for passing async data from parent to child? I've seen ngOnChanges used in places, but I'm not sure that's the right strategy either.

1
  • Is this true? That using the async pipe repeatedly throughout your a template is bad practice? I thought there was a benefit to it that you aren't manually managing subs... Commented Mar 3, 2017 at 21:23

1 Answer 1

3

You can use

<div class="page-header" *ngIf="page">

or the safe-navigation operator

<source [srcset]="page?.header?.desktop" media="(min-width: 1024)">
Sign up to request clarification or add additional context in comments.

2 Comments

If there are a lot of variables coming in, the *ngIf statement is the way to go. It seems like this is the standard practice being used across many of the learning platforms and developer experts. The safe nav operator works too!
Sure safe-nav works but if you have lots of bindings it can become cumbersome

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.