如何从组件中打开ng-template模态?
我有一个用ng-template包装的模式,
I have a modal wrapped in ng-template,
<ng-template #template>
<div class="modal-header">
<h4 class="modal-title pull-left">Modal for user id : {{ modalService.config.initialState.id }}</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
This is a modal.
</div>
</ng-template>
我有一个按钮可以像这样打开模式
i have a button to open this modal like
<button type="button" class="btn btn-primary" (click)="openModal(template)">Create template modal</button>
openModal(template: TemplateRef<any>) {
const user = {
id: 10
};
this.modalRef = this.modalService.show(template, {
initialState : user
});
}
这将在我将模板作为参数传递时起作用.
this will work as i am passing template as a parameter.
如何在不传递参数的情况下打开此模态?让它成为我没有按钮,我想在ngOninit上打开模态.怎么可能?
How can i open this modal without passing the parameter? let it be i dont have a button, i want to open the modal on ngOninit. How it is possible?
使用@ViewChild()
装饰器获取打字稿中模板的引用,并使用ngAfterViewInit()
钩子打开模式..
Get the reference of the template in typescript using @ViewChild()
decorator and use ngAfterViewInit()
hook to open the modal..
@ViewChild('template') templateRef: TemplateRef<any>;
ngAfterViewInit() {
const user = {
id: 10
};
this.modalRef = this.modalService.show(this.templateRef, {
initialState : user
});
}
https://stackblitz.com/edit/angular-modal-bootstap-pay2ua?file=app%2Fapp.component.ts
修改
我只是注意到,如果在ngAfterViewInit()
钩子中显示它,我们将得到一个ExpressionChangedAfterItHasBeenCheckedError
,以修复该包裹在setTimeuut()
I just noticed that we would be getting an ExpressionChangedAfterItHasBeenCheckedError
if we show it in ngAfterViewInit()
hook, to fix that wrap opening the modal in a setTimeuut()
setTimeout(() => {
this.modalRef = this.modalService.show(this.templateRef, {
initialState : user
})
})
https://stackblitz.com/edit/angular-modal-bootstap-pr377t?file=app/app.component.ts