【问题标题】:access Template Reference variable within ng-template访问 ng-template 中的模板引用变量
【发布时间】: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">&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
   }

【问题讨论】:

    标签: angular templates bootstrap-modal angular8 ng-bootstrap


    【解决方案1】:

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

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

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 2020-11-28
    • 2019-07-13
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多