How to pass data from modal to component?
I have a modal component and it looks like this:
<z-popup title="User search" #generaldetailHistoryModal modalSize="modal-lg" (onHideModal)="onHideModal()" footer="true">
<div content-type="body">
<z-grid [columns]="columnsUserSearchModal" [data]='users' paginator="true" (selectedItemClick)='setSelectedUser($event)'></z-grid>
</div>
</z-popup>
I have a preview component where I call this modal:
<user-search-modal [modalShown]="modalUserSearchShown" (onHide)="modalUserSearchShown=false"></user-search-modal>
Now I want to pass what I have selected in the modal preview component.
In modal.ts, I get the selected data:
setSelectedUser(event:any){
this.selectedData.emit(event);
}
But now I don't know how to pass this data for preview?
+3
source to share
1 answer
To avoid unnecessary code in components (keep bindings to inputs from (big) parent to child) and because you said that:
here i have a component inside a component and then i need to pass the value to the third component
I would use the service . Something like this (a working Plunkr example is here ):
modal.service.ts
import { Injectable, EventEmitter } from '@angular/core'; @Injectable() export class ModalService { public selectedUserChange = new EventEmitter() }
Other components (not just modular for simplicity)
import {Component, NgModule, OnInit} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' import {ModalService} from './modal.service' @Component({ selector: 'grand-child', template: ` <output *ngIf="user">{{ user }}</output> `, }) export class GrandChildComponent implements OnInit { private user constructor(public modalService: ModalService) { } ngOnInit() { this.modalService.selectedUserChange .subscribe((user) => { this.user = user }) } } @Component({ selector: 'child-component', template: ` <grand-child></grand-child> `, }) export class ChildComponent { } @Component({ selector: 'my-app', template: ` <div> <button (click)="setSelectedUser('bob')">set user to bob</button> <button (click)="setSelectedUser('amy')">set user to amy</button> </div> <child-component></child-component> `, }) export class App { constructor(public modalService: ModalService) { } setSelectedUser(user){ this.modalService.selectedUserChange.emit(user) } } @NgModule({ imports: [ BrowserModule ], declarations: [ App, ChildComponent, GrandChildComponent ], providers: [ ModalService ] bootstrap: [ App ] }) export class AppModule {}
+3
source to share