首页 > 解决方案 > Angular 5:从组件访问元素内部 html 以获取动态生成的元素

问题描述

我的组件中有一个角度组件,我需要访问元素的内部 html。为此,我可以使用带有模板引用的 ViewChild 为单个元素获取此信息。但是在 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>

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

标签: javascriptangularngforviewchild

解决方案


尝试这样的事情:

演示

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

推荐阅读