1

Trying to pass data to a child component, I can attach the property into the template, but cant seem to access the id inside the class of the component. Any ideas?

---PARENT---

   <related-products [id]="product.id"></related-products>

--CHILD---

import {Component, OnInit, Input} from 'angular2/core';
import {RouteParams, Router} from 'angular2/router';
import {ProductService} from '../products/product.service.js';

@Component({
  selector: 'related-products',
  templateUrl: "wp-content/themes/f2/app/views/directives/related-products-template.html",
  inputs: ['id'],
  providers: [ProductService]
})
export class RelatedProductsComponent implements OnInit {

  products: any[];
  errorMessage: string; 
  id: number;

  constructor(
    private _service: ProductService,
    private _router: Router,
    private _routeParams: RouteParams
  ) {}

  ngOnInit() {

    console.log(this.id);
  }

}

1 Answer 1

1

You could try to use @Input for the id property:

export class RelatedProductsComponent implements OnInit {
  products: any[];
  errorMessage: string;   
  @Input() // <------------
  id: number;

  (...)
}

but it should work with the inputs attribute and you should have access to the value in the ngOnInit hook method. Are you sure that the provided expression product.id returns something defined?

See this plunkr: https://plnkr.co/edit/aG4TdHbAls3cu04AAt64?p=preview.

Sign up to request clarification or add additional context in comments.

6 Comments

I think its the fact that i am making a ajax call to get the data, and this inturn means the data is not ready in the child component yet. How do i wait for the child component to be built so i know the data is available
You get the product directly or it's an element within a loop?
Its the single detail page, so I make the call and get the data and I have the child component (Related Products( which needs the id from the parent component (Product Detail)
parents data is not ready when the child component fires. Need a way of accessing the parent data from the child component when the data is available
And you don't have any error on the product.id expression? ;-) I think that product is initially undefined. Perhaps the Elvis operator could help you: product?.id. The value will be received later. Try to display it in the sub component into the ngOnChanges hook method...
|

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.