access Template ng-template内的引用变量



我在我的Angular项目中使用'@ng-bootstrap/ng-bootstrap'。

我有一个模态,模板引用变量是content,在模态模板中我有另一个模板变量oppGrid。我想访问oppGrid的元素,但我面临的问题,它似乎是空的。即使当我尝试使用ngAfterContentInit()和ngAfterViewInit()。那么我如何访问&在#oppGrid中做DOM操作,在ng模板中的模板引用变量?

//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">&times;</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
}

实际上答案一直在文档中https://stackblitz.com/run?file=src%2Fapp%2Fmodal-component.ts.

基本上创建一个处理Modal的新组件。然后在该组件中使用@ViewChild来访问那些htmlentity。

最新更新