angular - 如何在 Angular2+ 中修改 TemplateRef 的内容?
问题描述
如何修改文本内容或 TemplateRef 的 innerHTML?
我尝试在 Stackblitz 上关注:
# component.ts
import { Component, TemplateRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild("test", {read: TemplateRef})
public test: TemplateRef<any>;
constructor(){
// this.test.elementRef.nativeElement.innerHTML = "changed text" // <-- isnot working
}
}
# html.html
<ng-template #test>
<p>text content</p>
</ng-template>
<!-- to see if its working -->
<ng-container *ngTemplateOutlet="test"></ng-container>
目标:
我创建了一个包含给定 TemplateRef 的服务。然后我可以通过服务从其他组件获取这个 TemplateRef。得到这个之后,我想更改 innerHTML 并通过 DialogboxService 呈现 Ref。但我什至未能更改 ng-template 中的文本内容....
解决方案
html
<p #test > Some text </p>
组件.ts
@ViewChild('test') testcontainer: ElementRef<HTMLDivElement>
您可以在 ngAfterViewInit 中更改它
ngAfterViewInit() {
this.testcontainer.nativeElement.innerHTML = "changed text"
}
或者,如果您想使用函数调用进行更改
changeText() {
this.testcontainer.nativeElement.innerHTML = "changed text"
}
推荐阅读
- javascript - 如何将所选值从下拉列表传递到下一页中的另一个下拉列表
- database - MongoDB - 简单查询的性能瓶颈
- c# - Net Core:用于在通用存储库中将 Id 映射到 ClassName+Id 的 Automapper
- kivy - 更改 Kivy FileChooserIconView 的图标
- javascript - 传递:点击事件到动态创建
- python - Pygame:如何对图像进行 blit 和旋转以连接屏幕上的两个点?
- rust - 为什么多个线程在持有 Mutex 时使用太多内存
- html - 如何使 Mat-Grid-List 列属性动态化?
- angular2-mdl - MdlSelect - ViewDestroyedError:尝试使用已破坏的视图:detectChanges
- azure - 如何在 Azure Cache for Redis 中使用 RedisTimeSeries 模块?