0
votes

I have a parent component that is passing information to a child component, but it is undefined. I apologize if this is Angular 101, but how can I delay the child component from rendering or running any javascript until it has the input that it needs?

Parent component ngOnInit that pulls in data:

public ngOnInit(): void {
     this.productService.getProductById(1).subscribe(product => {
            this.product = product;
        });
}

Parent components HTML:

<child-component [product]="product" id="myProduct"></child-component>

Child component input declaration:

@Input() public product: Product;

Child component ngOnInit which required the product to be there:

public ngOnInit(): void {
     // It is returning as undefined
     console.log(this.product);
}
1
use setter and getter for @Input - Walter White

1 Answers

3
votes

This is because the products are loaded asynchronously, so when the view renders initially, the product is undefined

 <child-component *ngIf="product" [product]="product" id="myProduct"></child-component>

also you can use Onchanges

ngOnChanges(changes: SimpleChanges) {
    if (changes['product']) {
        let variableChange = changes['product'];
    }
}