如何使用 angular 中的 ng-bootstrap 将数据模态组件传递给父组件 4
How to pass data modal Component to parent Component using ng-bootstrap in angular 4
我尝试了以下编码,将数据从模态组件传递到父组件。
package.json
"@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.3"
app.component.html
<button class="btn btn-primary" (click)="openModal()">Open</button>
app.component.ts
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
export class AppComponent {
constructor(private modalService: NgbModal) { }
openModal() {
const modalRef = this.modalService.open(AppModalComponent);
}
}
app-modal.component.html
<h1>{{data}}</h1>
<button class="btn btn-primary" (click)="addMe()"></button>
app-modal.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
export class AppModalComponent {
private data: string;
@Output emitService = new EventEmitter();
constructor() {
this.data = "hello world";
}
addMe() {
this.emitService.next(this.data)
}
}
emit后如何获取父组件(app.component)中的数据??
您可以像这样订阅 emitService
@Output
:
openModal() {
const modalRef = this.modalService.open(AppModalComponent);
modalRef.componentInstance.emitService.subscribe((emmitedValue) => {
// do sth with emmitedValue
});
}
虽然上面的方法可行,但请注意,使用您想要 return 的值关闭模态通常更容易。这将解决 modalRef
上可用的承诺。
中的更多详细信息
我尝试了以下编码,将数据从模态组件传递到父组件。
package.json
"@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.3"
app.component.html
<button class="btn btn-primary" (click)="openModal()">Open</button>
app.component.ts
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
export class AppComponent {
constructor(private modalService: NgbModal) { }
openModal() {
const modalRef = this.modalService.open(AppModalComponent);
}
}
app-modal.component.html
<h1>{{data}}</h1>
<button class="btn btn-primary" (click)="addMe()"></button>
app-modal.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
export class AppModalComponent {
private data: string;
@Output emitService = new EventEmitter();
constructor() {
this.data = "hello world";
}
addMe() {
this.emitService.next(this.data)
}
}
emit后如何获取父组件(app.component)中的数据??
您可以像这样订阅 emitService
@Output
:
openModal() {
const modalRef = this.modalService.open(AppModalComponent);
modalRef.componentInstance.emitService.subscribe((emmitedValue) => {
// do sth with emmitedValue
});
}
虽然上面的方法可行,但请注意,使用您想要 return 的值关闭模态通常更容易。这将解决 modalRef
上可用的承诺。