我写了一个自定义modal
和一个modalService
,它提供了两个打开和关闭模态的功能。
现在,我有另一个名为select-list
组件的组件,我想做的是动态注入级联选择到模态viewContainerRef
,
让我感到困惑的是,当我通过模态确认 button
这是我的代码
modalComponent.ts
:
export class ModalComponent implements OnInit, AfterViewInit {
isOpened: boolean = false;
@Output() onCancel: EventEmitter<any> = new EventEmitter();
@Output() onConfirm: EventEmitter<any> = new EventEmitter(false);
// =======================
// 公共属性
// =======================
@ViewChild('modalRoot') modalRoot: ElementRef;
// =======================
// 私有属性
// =======================
@ViewChild('modalBody', {read: ViewContainerRef}) dynamicTarget: ViewContainerRef;
constructor() {
}
ngOnInit(): void {
this.modalService.registerModal(this);
}
ngOnDestroy() {
}
}
modalComponent.html
:
<!-- 弹层 S -->
<div class="modal-mask" [ngStyle]="{display: isOpened ? 'block': 'none'}"></div>
<div class="modal" role="popup-dialog" #modalRoot [ngStyle]="{display: isOpened ? 'block': 'none'}">
<div [class]="'modal-dialog ' + clazz" #modalDialog (click)="preventClosing($event)">
<div class="modal-content" tabindex="0">
<div class="modal-header">
<ng-content select="[modal-header]"></ng-content>
</div>
<div class="modal-body">
<span #modalBody></span>
</div>
<div class="modal-footer">
<button *ngIf="cancelButtonLabel.length > 0" (click)="cancel()" class="button cancel" #cancelButton [class.full-fill]="
!confirmButtonLabel">{{cancelButtonLabel}}</button>
<button *ngIf="confirmButtonLabel.length > 0" (click)="confirm()" class="button primary" #confirmButton [class.full-fill]="!cancelButtonLabel">{{confirmButtonLabel}}</button>
</div>
</div>
</div>
</div>
<!-- 弹层 E -->
modalService.ts
:
@Injectable()
export class ModalService {
// 弹层实例对象
private modal: ModalComponent;
private componentRef: ComponentRef<Component>;
private viewContainerRef: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
registerModal(newModal: ModalComponent): void {
this.modal = newModal;
}
// create<T>(module: any, component: any, params?: Object): Observable<ComponentRef<T>> {
// let componentRef$ = new ReplaySubject();
// }
open(component, opt?: Object): ModalComponent {
if (this.componentRef) {
this.componentRef.destroy();
}
// 动态加载其它组件
let factory = this.componentFactoryResolver.resolveComponentFactory(component);
this.componentRef = this.modal.dynamicTarget.createComponent(factory);
this.modal.isOpened = true;
return this.modal;
}
close(): void {
this.modal.isOpened = false;
}
}
然后,我在我的appComponent.ts
中执行此操作:
this.modalService.open(SelectListComponent);
appComponent.html
:
<mcare-modal #mcareModal
title="自定义弹窗"
cancelButtonLabel="取消"
confirmButtonLabel="确定"
(onConfirm)="actionOnConfirm($event)"
[modalId]="modalId">
<div modal-header>
<div class="row-control">
<h4 class="title">{{modalTitle}}</h4>
</div>
</div>
缩略图