I have an angular component in my component I need to access the inner html of element. For this I am able to get this for single element using ViewChild with template ref. but in the ngFor when I generate element and template ref dynamically it did not work. here is the error showed in console : -
Cannot read property 'native Element' of undefined
Here is the code for single element:-
@ViewChild('emailBodyContainer') emailBodyContainer: ElementRef;
<div [innerHtml]="emailTemplate.mailBody" #emailBodyContainer>
For dynamic elements: -
<div *ngFor="let i of reminderTemplates" class="container tab-pane text-center py-4 [innerHtml]="i.mailBody" #{{i.type}}></div>
Please help me to solve this. Thanks in advance :)
Try something like this:
DEMO
<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)
}
}
For Mat-Tab:
DEMO
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With