简体   繁体   中英

how to activate click event in a dom element (Angular 2)

I need to load a component at loading

<app-main id="tasks" [(ngModel)]="tasks"></app-main>

And the call from js

public tasks;
ngOnInit() {
    this.tasks.click();
}

I have tryed document.getElementById("tasks").click() and ngAfterViewInit()

To click the element, you can do the following:

Change your html to following:

<app-main id="tasks" #tasks></app-main>

... then in your component class:

import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
//...
@ViewChild('tasks') tasks:ElementRef;

ngAfterViewInit () {
    // Fire the click event of tasks
    this.tasks.nativeElement.click();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM