簡體   English   中英

從 Angular 父組件傳遞給子組件的數據在子組件中未定義

[英]Data passed from an Angular parent component to a child component is undefined in child component

我有一個將信息傳遞給子組件的父組件,但它是未定義的。 如果這是 Angular 101,我深表歉意,但是如何延遲子組件渲染或運行任何 javascript 直到它有它需要的輸入?

拉入數據的父組件 ngOnInit:

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

父組件 HTML:

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

子組件輸入聲明:

@Input() public product: Product;

需要產品存在的子組件 ngOnInit:

public ngOnInit(): void {
     // It is returning as undefined
     console.log(this.product);
}

這是因為產品是異步加載的,所以當視圖最初呈現時,產品是未定義的

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

你也可以使用 Onchanges

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM