我正在尝试将数据发送到自定义模式内容组件,以便我可以从任何其他组件调用它,而不是重复代码。我是 Angular 2 的新手,并且遵循了 ng-boostrap 的“组件作为内容”演示以及 Angular 文档中的“组件交互”,但尚未找到使其工作的方法或此案例的示例。
我可以打开模式,但不能打开动态内容。我已经尝试过@Input
和变量方法没有成功。我还添加了ModalService
给提供者app.module.ts
。这就是我对两种方法都不起作用的情况:
页面.组件.html:
<a (click)="modal('message')">
<template ngbModalContainer><my-modal [data]="data"></my-modal></template>
页面.组件.ts:
import { Component } from '@angular/core'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { ModalService } from '../helpers/modal.service'
import { ModalComponent } from '../helpers/modal.component'
@Component({
selector: 'app-page',
templateUrl: './page.component.html',
styleUrls: ['./page.component.scss'],
entryComponents: [ ModalComponent ]
})
export class PageComponent {
data = 'customData'
constructor (
private ngbModalService: NgbModal,
private modalService: ModalService
) { }
closeResult: string
modal(content) {
this.data = 'changedData'
this.modalService.newModal(content)
this.ngbModalService.open(ModalComponent).result.then((result) => {
this.closeResult = `Closed with: ${result}`
}, (reason) => {
this.closeResult = `Dismissed ${reason}`
});
}
}
模式.service.ts:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class ModalService {
private modalSource = new Subject<string>()
modal$ = this.modalSource.asObservable()
newModal(content: string) {
this.modalSource.next(content)
}
}
模态组件.ts:
import { Component, Input, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ModalService } from './modal.service'
@Component({
selector: 'my-modal',
template: `
<div class="modal-body">
{{data}}
{{content}}
</div>
`
})
export class ModalComponent implements OnDestroy {
@Input() data: string
content = 'hello'
subscription: Subscription
constructor(
private modalService: ModalService
) {
this.subscription = modalService.modal$.subscribe(
content => {
this.content = content
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
使用 Angular v2.1.0、Angular-cli v1.0.0-beta.16、ng-bootstrap v1.0.0-alpha.8