57

I want to pass data from HTML to the component so I've created an event like this:

<div id="tutor-price" (click)="passCharge(r.value['charge'])"><span id="month">월 8회</span> <span id="price"> {{r.value['charge']}} </span></div>

And in component:

passCharge(charge){
   this.charge = charge;
   console.log(this.charge,"give me the number")
}

If I click the event, I see everything's working fine. But I want to trigger this click event automatically since I want the component to use 'this.charge' value right away once the component is done the loading.

Is there any way I can trigger (click) event automatically?

4
  • 1
    Call the method? Commented Jul 11, 2017 at 6:53
  • 1
    You can call the method on ngOnInit() { } , it will be called once the page is loaded. Commented Jul 11, 2017 at 6:55
  • I can't just call the method passCharge(r.value['charge']); in ngOnInit() casue component can't read r.value['charge'] it won't compile If I add otheriwse, it doens't print what I want Commented Jul 11, 2017 at 7:17
  • What is r in your code? Commented Jul 11, 2017 at 7:20

5 Answers 5

103

Give it a ViewChild reference :

<div #myDiv id="tutor-price" (click)="passCharge(r.value['charge'])"><span id="month">월 8회</span> <span id="price"> {{r.value['charge']}} </span></div>

In your component :

@ViewChild('myDiv') myDiv: ElementRef<HTMLElement>;

triggerFalseClick() {
    let el: HTMLElement = this.myDiv.nativeElement;
    el.click();
}
Sign up to request clarification or add additional context in comments.

14 Comments

What is HTMLElement? I tried this but it's printing error ./MainComponent class MainComponent - inline template:57:8 caused by: Cannot read property 'nativeElement' of undefined
HTMLElement is an HTML element, what is usually returned by document.getElementById() in native JS. This error occurs because you didn't declare the elementRef.
By declare u meant this? 1.import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; 2. constructor( el:ElementRef) { } I tried both still the same error :(
@Xan because I explain, instead of giving the quickest solution.
this.myDiv.nativeElement; is undefined ?? doesn't work even after use after AfterViewInit in angular 7
|
11

You can trigger click event in ngOnInit() like this: `

<div #divClick id="tutor-price" (click)="passCharge(r.value['charge'])">
    <span id="month">월 8회</span> 
    <span id="price"> {{r.value['charge']}} </span>
</div>`

In component.ts file

import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
@Component({
  //component decoraters
})
export class MyComponent implements OnInit, AfterViewInit {
  @ViewChild('divClick') divClick: ElementRef;
  ngOnInit() {
      // your other code
    setTimeout(() => {
    this.divClick.nativeElement.click();
    }, 200);
  }
}

Comments

5

Expanding on the accepted answer, if you get the error "Cannot read property 'nativeElement' of undefined" or even "Cannot read property click of undefined", as OP clearly states in the comments to answer provided, use this solution:

If you want to get a reference of an element that hosts a component or directive you need to specify that you want the element instead of the component or directive

@ViewChild('myDiv', { read: ElementRef }) myDiv: ElementRef<HTMLElement>;

Comments

1

Just landed here from a research and I resolved to make my contribution to the topic. :)

You can create and dispatch an event too:

const domEl: HTMLElement = document.createElement('div'); 
// or do whatever you have to do to get the DOM Element

function triggerEvent(el: HTMLElement, evt: Event): void {
    if (el && evt) {
        const fakeEvent = new Event(evt, {bubbles: false, cancelable: false});

        el.dispatchEvent(fakeEvent);
    }
}

// adding some events to make this example more functional, 
// but do what you have to do to bind an event to your DOM Element

domEl.addEventListener('click', (ev) => { console.log('click', ev); });
domEl.addEventListener('focus', (ev) => { console.log('focus', ev); });
domEl.addEventListener('blur', (ev) => { console.log('blur', ev); });


triggerEvent(domEl, 'click'); // to dispatch click event
triggerEvent(domEl, 'focus'); // to dispatch focus event
triggerEvent(domEl, 'blur'); // to dispatch blur event

Hope that it helps you or someone else in the futures researches. :D

Comments

0
<div #tutor id="tutor-price" (click)="passCharge(tutor.value['charge'])"><span id="month">월 8회</span> <span id="price"> {{tutor.value['charge']}} </span></div>

Hope so this can help you ..

import { Component, OnInit } from '@angular/core';
tutor:any;
@Component({
      //your component decorater tags
})
export class MyComponent implements OnInit{
   ngOnInit(){
      this.charge = this.tutor.value['charge'];
   }
   passCharge(charge){
   this.charge = charge;

}

1 Comment

How would this even compile? passCharge(charge) and this.charge = charge is being done inside the class itself and not in any method?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.