I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Components as content" demo in ng-bootstrap and the "Component Interaction" section in the Angular documentation, I haven't been able to achieve this functionality or find a suitable example.
While I can successfully open the modal, integrating dynamic content has proven to be a challenge. I've experimented with both the @Input
approach and using variables, but unfortunately, neither method has yielded successful results. Additionally, I have included ModalService
in the providers within app.module.ts
. Here is what I have attempted with both strategies:
page.component.html:
<a (click)="modal('message')">
<template ngbModalContainer><my-modal [data]="data"></my-modal></template>
page.component.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}`;
});
}
}
modal.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);
}
}
modal.component.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();
}
}
Frameworks used include angular v2.1.0, angular-cli v1.0.0-beta.16, ng-bootstrap v1.0.0-alpha.8