Angular 2 - Passing data to Child component after Parent initialisation

后端 未结 5 2042
花落未央
花落未央 2020-12-23 16:58

I have a parent component which is getting data from a server through a service. I need some of this data to be passed to the Child component.

I\'ve been trying to p

5条回答
  •  臣服心动
    2020-12-23 17:38

    At the time your ChildComponent (you called it also ParentComponent, but i guess it's a typo) gets initialized and executes its ngOnInit, there is no data in your parent avaible since your service will still be out getting your data. Once your data is there it will be pushed to the child.

    What you can do depends on your usecase..

    If you just want to display the data in your ChildComponent template, you could use the elvis operator (?). Something like: {{ childData?}} or {{ childData?.myKeyName }}...

    If you want to do some other stuff, you may use a setter in your ChildComponent. It will intercept the input change and give you the opportunity to alter/test/"do what ever you want" with it before you do other things with it in your ChildComponent.. eg.:

    @Component({
        selector: 'test-child',
        template: `
            
        `
    })
    
    export class ChildComponent implements OnInit {
        private _childData: any;
        @Input()
        set childData(parentData: any) {
            // every time the data from the parent changes this will run
            console.log(parnetData);
            this._childData = parentData; // ...or do some other crazy stuff
        }
        get childData(): any { return this._childData; }
    
        ngOnInit() {
          // We don't need it for that...
        }
    }
    

    or use ngOnChanges as Madhu mentioned.

    You also might want to take a look at the cookbook entry for Component Communication in the official docs.

提交回复
热议问题