Angular 5:从组件中访问动态生成元素的内部HTML

5

我有一个Angular组件,需要访问元素的内部HTML。我可以使用ViewChild和模板引用获取单个元素的内部HTML,但在ngFor中动态生成元素和模板引用时无法正常工作。以下是控制台显示的错误:

Cannot read property 'native Element' of undefined

以下是单个元素的代码:

@ViewChild('emailBodyContainer') emailBodyContainer: ElementRef;
<div [innerHtml]="emailTemplate.mailBody" #emailBodyContainer>

对于动态元素:

<div *ngFor="let i of reminderTemplates" class="container tab-pane text-center py-4 [innerHtml]="i.mailBody" #{{i.type}}></div>

请帮我解决这个问题。 提前致谢 :)

2个回答

2
尝试像这样做:

演示


注:此链接为一个演示页面。
<div *ngFor="let i of arr;let j = index" id=item{{j}}>
    {{i}}
</div>

TS:

  import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  arr: Array<any> = [1, 2, 3, 4]

  ngAfterViewInit() {
    let data1 = document.getElementById('item0')
    let data2 = document.getElementById('item1')
    let data3 = document.getElementById('item2')
    let data4 = document.getElementById('item3')
    console.log(data1)
    console.log(data2)
    console.log(data3)
    console.log(data4)
  }
}

针对Mat-Tab:

演示

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  @ViewChild("main") main: ElementRef;

  name = 'Angular';
  Tabs: Array<any> = [{ name: 'Tab1' }, { name: 'Tab2' }, { name: 'Tab3' }]

  ngAfterViewInit() {
    let el = document.getElementById("main");


    console.log(el);

    let elh = el.children.item(0).children.item(1).children.item(0).children.item(0).children;

    elh.item(0).setAttribute("style", "color:red;")

    elh.item(1).setAttribute("style", "color:green;")

    elh.item(2).setAttribute("style", "color:cyan;")
  }

}

HTML:

<mat-tab-group id = "main">
    <mat-tab *ngFor="let tab Of Tabs;let i= index" [label]="tab.name"> Content {{i}} </mat-tab>
</mat-tab-group>

它已经适用于单个组件。但是我在动态生成的元素中遇到了问题。 - Khemraj
see demo above. - Akj
它对我不起作用。供您参考,我在MatTab中使用了ngfor。 - Khemraj
谢谢你的回答。我的问题已经解决了。我的问题是当前选定的标签页。 - Khemraj

1
You can use something like this.

<div *ngFor="let i of reminderTemplates" class="container tab-pane text-center py-4 [innerHtml]="i.mailBody" #items></div>

In component:

@ViewChildren('items') items: QueryList<ElementRef>;

console.log(this.items); // print the list of items

感谢您的回复。它适用于您的情况,但在以下情况下无法正常工作: this.items.forEach(item =>{ console.log(item.nativeElement.innerHTML); }); - Khemraj
你好Suresh,你有以上问题的解决方案吗? - Khemraj
请检查您的代码,它是否能够正常工作?对我来说它无法工作。 - Khemraj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接