Reputation: 742
I am having trouble to make two components communicate in Angular, and I can't see where I am making a mistake.
To be more specific I have a table(one component) and I want on click on a row to open a modal window(separate component) with the clicked row details. I have done all the wiring the modal window opens but no data is displayed.
export class TableComponent implements OnInit {
posts: Post[];
selected: any;
selectRow(post) {
this.selected = post;
document.getElementById('modalActivator').click();
}
private setPosts(posts) {
this.posts = posts;
}
constructor(
private restCallService: RestCallService
) {}
ngOnInit() {
this.restCallService.getPosts().then(posts => this.setPosts(posts))
}
}
Table HTML:
<table>
<tbody>
<tr *ngFor="let post of posts;"
(click)="selectRow(post)">
<td>{{post.userId}}</td>
<td>{{post.id}}</td>
<td>{{post.title}}</td>
</tr>
</tbody>
</table>
<app-table-row-expanded> [postFromParent]="selected"</app-table-row-expanded>
The modal is not opened optimally but could this be the problem for no data communication?
export class TableRowExpandedComponent implements OnInit {
@Input() postFromParent: Post
constructor() {}
ngOnInit() {}
}
I will spare you the whole modal HTML. This is what sits in the modal body:
<p>{{postFromParent?.body}}</p>
Any help would be appreciated.
PS, I am using Angular CLI with Eclipse, and already some weird bugs have appeared (running code not compiling unless I close and reopen the file ie. but this doesn't feel to be the issue here)
Upvotes: 1
Views: 483
Reputation: 6141
There's a slew of ways to get this to behave how you want. My favorite for a modal is to expose a public open method in the modal component. This will let you call it directly with data based on any conditions you like. As example setup could be
export class TableComponent {
@ViewChild('modal') modal;
selectRow(post) {
this.modal.open(post);
}
}
<app-table-row-expanded #modal> [postFromParent]="selected"</app-table-row-expanded>
The #modal provides a reference to your component which is accessed by the @ViewChild decorator. Now you just need to create your open method in the modal component as such
export class TableRowExpandedComponent implements OnInit {
public open(post) {
// whatever logic to display your stuff here
}
}
You'll also be able to access any @Inputs posted to the component normally
Upvotes: 2