angular - 访问 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">×</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。
基本上创建一个处理模态的新组件。然后在该组件中正常使用@ViewChild 来访问这些HTMLEntities。
推荐阅读
- google-sheets - 使用 Countifs 计算一个范围内的值的数量,获取 COUNTIFS 的数组参数的大小不同
- nginx - 如何在 nginx 中的主机后添加 url 前缀?
- python - 为目录中的所有测试添加设置步骤,而不在每个套件中添加
- google-apps-script - MailApp 错误:我尝试发送的每封电子邮件都出现“邮件被拒绝”
- python - 避免使用两个嵌套的 for 循环以提高性能
- python - Mixin 中的属性可以成为嵌套对象吗?
- angularjs - 找不到 `package.json` 文件。确保您在 Node.js 项目中运行该命令
- sql-server - MSSQL - 在所有存储过程中查找和替换文本
- html - Node.js 和 Mustache.js:如何将服务器端渲染与客户端 mustache 模板分开?
- r - 精确计算多次出现