如何将数据从模态传递给组件?

时间:2017-05-11 06:53:56

标签: angular

我有模态组件,它看起来像这样:

<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>

我有预览组件,我称之为模态:

<user-search-modal [modalShown]="modalUserSearchShown" (onHide)="modalUserSearchShown=false"></user-search-modal>

现在我想要的是将我在模态中选择的内容传递给预览组件。

在modal.ts中,我得到了选定的数据:

  setSelectedUser(event:any){
        this.selectedData.emit(event);
    }

但现在我不知道如何将数据传递给预览组件?

1 个答案:

答案 0 :(得分:4)

为了避免组件中不必要的代码(保持绑定到(大)父对子的输入)并且因为你说过:

  

这里我有组件内部组件,然后我需要将值传递给第三个组件

我会use a service。这样的事情(working Plunkr example here):

  

<强> modal.service.ts

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class ModalService {
  public selectedUserChange = new EventEmitter()
}
     

其他组件(为简单起见未模块化)

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 {}