Is there any way I can pass dynamic data to a component in Angular?

前端 未结 4 1878
抹茶落季
抹茶落季 2021-01-12 20:42

I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

ParentComp

4条回答
  •  难免孤独
    2021-01-12 20:59

    You might try OnChanges lifecycle hook method.

    In your case, you would need to add it to your child component like so:

    ngOnChanges(changes) {
      if (changes['dataNeeded'] && this.dataNeeded) {
        console.log(this.dataNeeded);
      }
    }
    

    PS Also I just noticed the wrong syntax in your ChildComponent.ts, it is missing this:

    ngOnInit() {
     console.log(this.dataNeeded);
    }
    

提交回复
热议问题