javascript - 'Click' function not working within typescriptangular after finding element using 'document

I have an element on a page in my Angular 8 Project.This element has an attribute of 'data-convo-i

I have an element on a page in my Angular 8 Project.

This element has an attribute of 'data-convo-id' with a unique string attached to it.

On this element is a click function that will load data based off of the data attribute that is also on that element (as described above).

Because I won't strictly have access to this element, I need a way of finding the element on this page using 'document.querySelector()', and then triggering a click on it. This in turn will fire off the function attached to that element, which will load the data as requested.

I've tried two different methods of doing this and both don't work. See below.

Method 1:

// This gets the ID that we're looking for from the NgRx Store.
const currentID = this.State$.currentId;

// This finds the element on the page with the data attribute, plus the ID from above.
const relevantElem: HTMLElement = document.querySelector(`[data-convo-id=${currentID}]`) as HTMLElement;

// Simulate click on that element.
relevantElem.click();

Method 2:

// Create the event
let event = document.createEvent("HTMLEvents");

// Tie the event to 'click'
event.initEvent("click", true, true);

// This gets the ID that we're looking for from the NgRx Store.
const currentID = this.State$.currentId;

// This finds the element on the page with the data attribute, plus the ID from above.
const relevantElem: HTMLElement = document.querySelector(`[data-convo-id=${currentID}]`) as HTMLElement;

// Simulate click event on that element.
relevantElem.dispatchEvent(event);

For reference, here is the HTML element itself:

<p #el [attr.data-convo-id]="conversation.id" (click)="viewConversation(el)"><strong>VIEW</strong></p>

In summary, both click events do nothing. Even if I add a 'SetTimeout' function along with a console log to ensure it is clicked after a decent amount of time, and the click is still ignored.

I get zero errors with the above code.

I have an element on a page in my Angular 8 Project.

This element has an attribute of 'data-convo-id' with a unique string attached to it.

On this element is a click function that will load data based off of the data attribute that is also on that element (as described above).

Because I won't strictly have access to this element, I need a way of finding the element on this page using 'document.querySelector()', and then triggering a click on it. This in turn will fire off the function attached to that element, which will load the data as requested.

I've tried two different methods of doing this and both don't work. See below.

Method 1:

// This gets the ID that we're looking for from the NgRx Store.
const currentID = this.State$.currentId;

// This finds the element on the page with the data attribute, plus the ID from above.
const relevantElem: HTMLElement = document.querySelector(`[data-convo-id=${currentID}]`) as HTMLElement;

// Simulate click on that element.
relevantElem.click();

Method 2:

// Create the event
let event = document.createEvent("HTMLEvents");

// Tie the event to 'click'
event.initEvent("click", true, true);

// This gets the ID that we're looking for from the NgRx Store.
const currentID = this.State$.currentId;

// This finds the element on the page with the data attribute, plus the ID from above.
const relevantElem: HTMLElement = document.querySelector(`[data-convo-id=${currentID}]`) as HTMLElement;

// Simulate click event on that element.
relevantElem.dispatchEvent(event);

For reference, here is the HTML element itself:

<p #el [attr.data-convo-id]="conversation.id" (click)="viewConversation(el)"><strong>VIEW</strong></p>

In summary, both click events do nothing. Even if I add a 'SetTimeout' function along with a console log to ensure it is clicked after a decent amount of time, and the click is still ignored.

I get zero errors with the above code.

Share Improve this question edited Sep 30, 2021 at 10:28 Guerric P 31.9k6 gold badges58 silver badges106 bronze badges asked Jan 10, 2020 at 8:49 Jamie BohannaJamie Bohanna 5601 gold badge8 silver badges28 bronze badges 2
  • 2 You said you don't have access to the element but <p #el [attr.data-convo-id]="conversation.... line shows you do. You have set (click) event and template variabe on it, don't you? – Vega Commented Jan 13, 2020 at 9:31
  • instead of document.queryselector,can you create an angular directive and handle the click event there ? this directive can be applied to the html element explicity – boredbear153 Commented Jan 19, 2020 at 13:11
Add a ment  | 

3 Answers 3

Reset to default 4 +25

You should avoid using native JavaScript API as much as possible when using Angular.

Try this instead:

//In your ponent class properties
@ViewChildren('el') elList: QueryList<ElementRef>;

//In the relevant part of your code
this.elList.find(x => x.nativeElement.getAttribute('data-convo-id') == currentID).click();

Are you successfully getting the element you want?

If so, you need to add the following:

document.querySelector(/**/).addEventListener('click', callbackfn)

and in your ponent add the function

callbackfn(event: Event): void { console.log(event); console.log(this); }

I add console.log(this) to show that you aren't operating from within the angular ponent any more, so you need to pass any services or variables you want in the function as part of the element like so:

const el = document.querySelector(/**/) as any;
el.router = this.router //add angular router, for example

and then in your callback you can do something like this:

callbackfn(event: Event): void {
  event.preventDefault(); //if you don't want the click to propagate
  const target = event.currentTarget as any;
  const router = target.router as Router;
  //do the thing you want to do with your service, in this case angular router
}

For querySelector([data-convo-id=${currentID}]), we can not simply get the dom element by its custom data attribute. We have to say the corresponding tag name as well. (i.e)

document.querySelector(p[data-convo-id="${currentID}"])

Please refer to my code sandbox (app.ponent.ts) example. I am not expert in angular. But I have tried with static currentID and it is working :-).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745668511a4639261.html

相关推荐

  • 论文检测,文章检测,降AI率的工具

    1:文字滚筒鸭文字滚筒鸭作为市面上少见的全免费平台,文字滚筒鸭支持文章 AI 率检测、头条文章原创度分析、作文质量评估等多元场景,甚至能一键对比原文与改写后的相似度,所有功能统统 0 收费!精准算法秒出检测结果,不用充值会员,也无需分享裂变

    1小时前
    20
  • 开发体育直播系统后台权限设计实践分享|ThinkPHP 技术栈落地案例

    今天我们分享的是一套由 东莞梦幻网络科技 自研的体育直播源码,在 ThinkPHP + MySQL 技术栈的加持下,后台权限系统如何从0到1落地,并支撑整个平台稳定运行。一、整体架构设计代码语言:html复制用户端(APPH5P

    1小时前
    20
  • 流固耦合:基本概念、适用软件及 Abaqus 与 Powerflow 的协同仿真

    在工程和科学研究的诸多领域,流固耦合现象广泛存在且对系统性能有着关键影响。理解流固耦合的本质及其应用,对于优化设计、保障安全运行意义重大。同时,借助专业的流固耦合软件,能够更高效地对相关问题进行分析与模拟。接下来,让我们深入探究流固耦合的奥

    1小时前
    00
  • 电脑分区后进不了系统怎么办,修复教程

    电脑分区后进不了系统&#xff0c;可能的原因有多种&#xff0c;包括分区操作不当导致系统文件丢失或损坏、BIOS设置错误、引导文件未正确配置等。针对这些问题&#xff0c;可以尝试以下解决方法&#xff1

    59分钟前
    00
  • UMIT:统一多模态多任务视觉

    随着深度学习的迅速发展,尤其是在医学影像分析领域的应用,越来越多的视觉-语言模型(VLMs)被广泛应用于解决复杂的健康和生物医学挑战。然而,现有研究主要集中在特定任务或单一模态上,这限制了它们在多种医学场景中的适用性和泛化能力。为了解决这

    57分钟前
    00
  • 电脑密码在哪里设置win11,win11电脑开机密码怎么设置

    Win11系统由于许多设置和以前系统不一样了&#xff0c;所以很多用户们操作非常不习惯&#xff0c;有很多的小伙伴不知道win11系统怎么设置开机密码。给电脑设置密码&#xff0c;只有自己能打开进入系统桌面&a

    46分钟前
    00
  • 初始JESD204B高速接口协议(JESD204B一)

    01、对比LVDS与JESD204JESD204B是逻辑器件和高速ADCDAC通信的一个串行接口协议,在此之前,ADCDAC与逻辑器件交互的接口大致分为如下几种。低速串行接口(I2C、SPI)、低速并行接口(包含时钟信号和并行数据信号,

    44分钟前
    00
  • 国产之光!!让你的Docker管理更优雅!

    大家好,我是热爱开源的了不起!我们都知道,Docker是个好东西,能帮我们把应用打包成容器,方便部署和管理。但问题来了,Docker的命令行操作对新手来说有点复杂,一不小心就容易出错。而且,有时候我们只是想简单地管理一下容器,却得记住一堆命

    39分钟前
    00
  • 如何打造高效AI智能体?

    作者|Barry Zhang, Anthropic地址|出品|码个蛋(ID:codeegg)整理|陈宇明最近看到了 Anthropic 那篇著名的《Building effective agents》作者之一 Barry Zhang 在 2

    35分钟前
    00
  • 非nvidia卡torchvision报错修复: operator torchvision::nms does not exist

    在Ascend 910b上安装vllm, 会自动把torchaudio和torchvision安装上去.安装前代码语言:shell复制pip list | grep torchtorch

    34分钟前
    00
  • 国产车载通信测试方案:车规级CAN SIC芯片测试技术解析

    随着智能网联汽车的快速发展,车辆内部电子控制单元(ECU)数量激增,动力总成、高级驾驶辅助系统(ADAS)、车身控制等功能对车载通信网络的稳定性与速率提出了更高要求。传统CAN FD总线在复杂拓扑中面临信号振铃、通信速率受限(实际速率通常低

    27分钟前
    00
  • Prometheus配置docker采集器

    Prometheus 配置 Docker 采集器Prometheus 是一个开源的监控系统和时间序列数据库,广泛用于容器化环境中。通过监控 Docker 容器,用户可以实时获取服务性能、资源使用情况等信息。本文将介绍如何为 Docker 容

    22分钟前
    00
  • ascend pytorch 踩坑.

    在910b上安装pytorch 和 pytorch_npu, 因为后续准备装vllm, 所以torch_npu是特殊的版本.代码语言:shell复制pip install torch==2.5.1 --extra-index pip in

    21分钟前
    00
  • Power BI 无公式实现帕累托图表

    帕累托分析(Pareto Analysis),也被称为8020法则、关键少数法则,是一种常用的管理工具,用于识别和处理影响业务的主要因素。看到李伟坚老师在Excel使用Vega实现了花式帕累托(参考:Excel 零公式实现高级帕累托图表)

    18分钟前
    00
  • Go 语言 Mock 实践

    Mock 是软件测试中的一项关键技术,尤其在单元测试领域,可谓是“顶梁柱”般的存在,几乎不可或缺。它通过模拟真实对象的行为,使我们能在不依赖外部系统的情况下,专注测试代码的核心逻辑。对于测试开发、自动化测试,乃至性能测试中的某些场景,合理使

    16分钟前
    00
  • 如何快速判断 Flutter 库是否需要适配鸿蒙?纯 Dart 库无需适配!

    在鸿蒙开发中,选择合适的 Flutter 库至关重要。纯 Dart 库因其跨平台特性,无需适配即可直接使用。但对于新手来说,如何判断一个库是否为纯 Dart 库呢?本文将为你提供清晰的判断方法和实用技巧。一、检查 pubspec.yaml

    14分钟前
    00
  • MongoDB “升级项目” 大型连续剧(2)

    上期写的是非必要不升级,想到这个事情,有一些事情的仔细琢磨琢磨,为什么数据库升级的事情在很多公司都是一个困扰,从一个技术人的观点,升级是一件好事,功能提升了,性能提升了,开发效率和一些数据库使用的痛点也被解决了,为什么就不愿意升级呢?如果只

    13分钟前
    00
  • 推荐一个轻量级的监控平台并且支持移动端

    简介XUGOU 是基于Cloudflare构建的轻量化监控平台,专精于系统资源监控与可视化状态页面服务。该平台提供英文简体中文双语支持,满足全球化部署需求。面向开发者及中小团队,项目致力于提供高可用性的监控解决方案。核心功能与实现平台功能

    5分钟前
    00
  • module &#x27;torch.

    踩坑Ascend, 安装 pytorch 2.5.1 和 pytorch_npu 2.5.1, import torch 报错.执行 python -c "import torch;import torch_npu;"时

    3分钟前
    00
  • 【Docker项目实战】使用Docker部署IT工具箱Team·IDE

    一、Team·IDE介绍1.1 Team·IDE简介Team IDE 是一款集成多种数据库(如 MySQL、Oracle、金仓、达梦、神通等)与分布式系统组件(如 Redis、Zookeeper、Kafka、Elasticsearch)管理

    2分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信