作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有模态组件,它看起来像这样:
<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);
}
但现在我不知道如何将这些数据传递给预览组件?
最佳答案
为了避免组件中不必要的代码(保持绑定(bind)到从(大)父级到子级的输入)并且因为你已经说过:
here i have component inside component, and then i need to pass value to third component
我会 use a service .像这样 ( working Plunkr example here ):
modal.service.ts
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class ModalService {
public selectedUserChange = new EventEmitter()
}The other components (not modularized 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 {}
关于angular - 如何将数据从模态传递到组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43908461/
我是一名优秀的程序员,十分优秀!