2

I have a child and a parent component.

I want to pass an array from the child component and display it in the parent component.

I first started with:

@Input data: string[];

Then in ngOnInit I have:

ngOnInit() {
   this.data = ['name1', 'name2', 'name3'];
}

Then I have the parent component:

<app.parent></app.parent>

My question is: how do I display this data in the parent component?

0

1 Answer 1

13

You should be using @Output() as below,

@Output() data: EventEmitter<string[]> = new EventEmitter<string[]>();

ngOnInit() {
   this.data.emit(['name1', 'name2', 'name3']);
}

you should be handling the event in your parent as

<app.parent (data)="eventHandler($event)"></app.parent>

eventHandler(event:string[]){
     this.childData = event;
}

Display the childData in your component as

{{childData}}
Sign up to request clarification or add additional context in comments.

5 Comments

I'm confused on which parts of the code go in which files...can you please specify?
Can you create a plunker to reproduce your error. I'll write on top of it and help you
I've deleted all me code and I'm going to use your code. I have child-component and parent-component and also the app.component ... You have 3 sections in your code. I just need to know what files they go into. Could you just specify that?
First code should be in your child and remaining code should be in your typescript and html of parent component
childData does not exist on parent component