就我而言,我在组件中使用 ngBaseDef.inputs.data。
参见示例:
import {Component, Injectable, Input} from '@angular/core';
import {NgbActiveModal, NgbModal} from "@ng-bootstrap/ng-bootstrap";
import {ExampleComponent } from "../components/modals/moder-info/example.component";
@Component({
selector: 'modal-template',
template: `
<div class="modal-header">
<h4 class="modal-title" [innerText]="title"></h4>
<button type="button" class="close" aria-label="Close" (click)="close()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ng-content *ngComponentOutlet="childComponent;"></ng-content>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="close()">Close</button>
</div>
`
})
export class ModalTemplate {
@Input() title;
@Input() onClose;
@Input() childComponent;
constructor(public activeModal: NgbActiveModal) {}
close() {
this.activeModal.dismiss('close');
this.onClose();
}
}
export interface ModalServiceOptions {
data: any;
title: string
onClose: any,
componentName: string
}
@Injectable({
providedIn: 'root'
})
export class ModalService {
constructor(private mService: NgbModal) {}
open(options: ModalServiceOptions) {
let types = {'example': ExampleComponent };
let modal = this.mService.open(ModalTemplate, {size: 'lg'});
modal.componentInstance.title = options.title;
modal.componentInstance.onClose = options.onClose;
let component = types[options.componentName];
component.ngBaseDef.inputs.data = options.data;
modal.componentInstance.childComponent = types[options.componentName];
}
}
示例组件
import {Component, Input, OnInit} from '@angular/core';
@Component({
selector: 'example-component',
templateUrl: './example.component.html',
styleUrls: ['./example.component.sass']
})
export class ExampleComponent implements OnInit {
@Input() data;
constructor() {
let dataOfConstructor: any = this.constructor;
let data = dataOfConstructor.ngBaseDef.inputs.data;
console.log('data:', data); // Here is my data, i injected it above
}
ngOnInit() {
}
}
祝你今天过得愉快!希望能帮助到你!