首页 > 解决方案 > 访问 ng-template 中的模板引用变量

问题描述

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

我有一个模板引用变量是模态的,content并且在该模态模板中我有另一个模板变量oppGrid。我想访问 elementRef ,oppGrid但我遇到了问题,它似乎为空。即使我尝试使用 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">&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
   }

标签: angulartemplatesbootstrap-modalangular8ng-bootstrap

解决方案


实际上,答案在所有这些文档中,而https://stackblitz.com/run?file=src%2Fapp%2Fmodal-component.ts

基本上创建一个处理模态的新组件。然后在该组件中正常使用@ViewChild 来访问这些HTMLEntities。


推荐阅读