javascript - 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>
请帮我解决这个问题。提前致谢 :)
解决方案
尝试这样的事情:
<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>
推荐阅读
- postgresql - 重置服务器后如何恢复 postgresql 数据库
- solr - SOLR Cassandra 查询是否预计会详尽无遗?
- r - 基于 R 中的另一列对列的所有组合求和
- python - 在将字段名称与现有列连接时转置/堆栈/取消堆栈熊猫数据帧
- android - 如何使用 NotifyItemInsert() 和 NotifyItemDataChanged() 方法在 RecyclerViewAdapter 上处理更新数组
- vue.js - 如何配置在 ie 11 上运行的 Nuxt.js
- android - RecyclerView Card 双向展开
- angular - 角度如何访问ngClass的formgroup属性
- r - 在 R 4.0 与 3.6.1 中的 Shiny App 中采购外部 R 脚本
- azure - Kubernetes 上的高可用、冗余 Redis 集群