简体   繁体   English

从 Angular 父组件传递给子组件的数据在子组件中未定义

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

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?如果这是 Angular 101,我深表歉意,但是如何延迟子组件渲染或运行任何 javascript 直到它有它需要的输入?

Parent component ngOnInit that pulls in data:拉入数据的父组件 ngOnInit:

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

Parent components HTML:父组件 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:需要产品存在的子组件 ngOnInit:

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

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你也可以使用 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