Reputation: 1285
Hi I'm trying to get data(that has been extracted after ngFor) from html using viewChildren and elementRef but I'm getting
Cannot read property 'nativeElement' of undefined
What am I doing wrong? I am also using ngAfterViewInit
These are my code (html)
<div id="tutor-price" #myDiv (click)="passCharge(r.value['charge'])"><span id="month">8 Times a month</span> <span id="price"> {{r.value['charge']}} </span></div>
Component
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router'
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
let el: HTMLElement = this.myDiv.nativeElement as HTMLElement;
el.click();
}
by doing above, I'd like to toggle click event automatically when the component is done loading.
But I'm getting error.
what am I doing wrong?
Upvotes: 2
Views: 8945
Reputation: 144
use ViewChild variable after View has initialized, i.e. use -
ngAfterViewInit()
Upvotes: 2
Reputation: 71961
You assign the template variable to a normal HTMLElement
and not to a component tag, this will make the myDiv
field property a HTMLElement
and not an ElementRef
:
@ViewChild('myDiv')
myDiv: HTMLDivElement;
ngAfterViewInit() {
el.click();
}
Upvotes: 2