【发布时间】:2021-09-05 08:06:31
【问题描述】:
我在我的 Angular 项目中使用“@ng-bootstrap/ng-bootstrap”。
我有一个模态,其模板引用变量是content,在该模态模板内我有另一个模板变量oppGrid。我想访问 oppGrid 的 elementRef 但我遇到了问题,它似乎为空。即使我尝试使用 ngAfterContentInit() 和 ngAfterViewInit()。那么如何在#oppGrid(ng-template 中的模板引用变量)中访问和进行DOM 操作?
//app.component.html code
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Profile update</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body p-0 m-0">
<div class="container p-0 m-0">
<div class="row p-0 m-0 justify-content-center">
<div #oppGrid class="col-lg-6 p-0 m-0 border border-primary">
HELLO WORLD 1
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">CLOSE</button>
</div>
</ng-template>
//app.component.ts
import { Component,ElementRef, ViewChild, AfterViewInit, ContentChild, AfterContentInit} from '@angular/core';
import {NgbModal, NgbModalRef} from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit, AfterContentInit{
modalRef:NgbModalRef;
@ViewChild("content") gameModal:ElementRef;
@ContentChild('oppGrid') oppGrid: ElementRef;
constructor(private modalService: NgbModal){
}
ngAfterViewInit(){
this.modalRef = this.modalService.open(this.gameModal,{size:"xl"});
console.log(this.gameModal);//works
this.modalRef.shown.subscribe(()=>{
console.log(this.oppGrid);//undefined
});
console.log(this.oppGrid);//undefined
}
ngAfterContentInit(){
console.log(this.oppGrid);//undefined
}
}
我也尝试过将 oppGrid 改为 @ViewChild
...
@ViewChild('oppGrid') oppGrid: ElementRef;
....
ngAfterViewInit(){
console.log(this.gameModal);//works
console.log(this.oppGrid);//undefined
}
【问题讨论】:
标签: angular templates bootstrap-modal angular8 ng-bootstrap