首页 > 解决方案 > 如何在 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 中的文本内容....

标签: angular

解决方案


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"
  }

推荐阅读