The reason for not being able to access the template DOM element within the constructor of the component

Exploring RxJS and attempting to create a basic stream of button clicks, I tried the following approach:

export class AppComponent {

    button : HTMLElement = document.querySelector('button');

    refreshClickStream$ = Observable.fromEvent(this.button, 'click')
       .subscribe();

    constructor(){
    }  

However, upon execution, an error was displayed in the console.

I then made another attempt using this method:

  clicked(e) {
    return Observable.fromEvent(e.target, 'click')
    .do(console.log)
       .subscribe();
  }

After the first click, no output appeared in the console. Subsequent clicks resulted in one MouseEvent object after the second click, two MouseEvent objects after the third click, three MouseEvent objects after the fourth click, and so on. It seems like the click event handler may be duplicating with the RxJS fromEvent function.

If anyone has any insights or explanations, they would be greatly appreciated.

Answer №1

Your current setup is as follows:

AppComponent 
   template: '<button>some button</button>'
   button : HTMLElement = document.querySelector('button');

The code at the top level of your class will become the body of the constructor when transpiled to JavaScript:

class AppComponent {
   constructor() {
       let HTMLElement = document.querySelector('button');
   }
}

When Angular traverses through the component tree, it creates a view with DOM nodes for each component sequentially. Initially, it generates a view for the outermost component that hosts app-component. It then sets up a DOM host element for it and triggers the AppComponent constructor. The view for AppComponent containing the button DOM element is not yet created at this stage. Therefore, attempting to find the button DOM element in the constructor results in an error.

To achieve what you intend to do, utilize any of the lifecycle hooks available. For more details, refer to my response on the topic "Difference between Constructor and ngOnInit" here.

In addition to addressing this issue, I recommend using @ViewChild for the DOM query and implementing the ngOnInit lifecycle hook as shown below:

template: `<button #b>...</button>`
...
class AppComponent {
   @ViewChild('b') button;

   ngOnInit() {
       this.refreshClickStream$ = Observable.fromEvent(this.button, 'click').subscribe();
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to store the current router in a state for later use

I am currently working on implementing conditional styling with 2 different headers. My goal is to save the current router page into a state. Here's my code snippet: const [page, setPage] = useState("black"); const data = { page, setPage, ...

Utilize Angular Material's Progress Bar within your Snack Bar component

I'm currently trying to incorporate an angular material progress bar inside my angular material snackbar. The purpose of the progress bar is to function as a countdown, meaning that if the snackbar remains open for 5 seconds, the progress bar should v ...

Leveraging Angular Universal Prerendering to fetch content from /static/data.json using the httpClient module

I am currently exploring how to prerender a component using Angular Universal, which involves fetching data with httpClient from the app's /static folder. How can I correctly utilize httpClient in Angular Universal? Is it feasible to access static r ...

Limit the types of function parameters to only one option within a union type parameter

I have a collection of tuples that I can use to define variables: type KnownPair = ["dog", "paws"] | ["fish", "scales"]; const goodPair: KnownPair = ["dog", "paws"]; //@ts-expect-error you cannot mix them: const badPair: KnownPair = ["dog", "scales"]; I ...

Presenting data in various formats

I've got a JSON file with a list of data that includes months and years. I want to display all the months, but have the year only appear once in a big block area. Here's an image example: https://i.stack.imgur.com/Ps3OF.png The image demonstrates ...

Angular 15 is unfortunately not compatible with my current data consumption capabilities

I'm currently facing an issue with Angular 15 where I am trying to access the "content" element within a JSON data. However, when attempting to retrieve the variable content, I am unable to view the elements it contains. import { Component, OnInit } ...

Managing alerts in Protractor

I encountered a challenge while trying to handle an alert using Protractor. My goal is to navigate to another page after accepting the alert, but my attempts have not been successful so far: (PS, if I remove the failing tests, all other tests work fine) (P ...

Implementing debounce in Subject within rxjs/Angular2

I am currently building an events service, and here is the code snippet I am using: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; export int ...

I must remove the thumb from the input range control

I am looking for a way to remove the thumb from the progress bar in my music player. I have tried various methods without success, and I simply want the progress bar to move forward with color change as it advances based on the Progress variable. For refe ...

Concealing input special characters with Angular 8

Is there a way to display credit card numbers in an input field with a bullet special character look? 4444 •••• •••• 4444 I'm attempting to achieve this using a pipe in Angular without relying on any input mask plugins. Here's w ...

An issue arises with launching karma.js when importing node-openid-client in a TypeScript specification file

Utilizing the node-openid-client library for OpenIDConnect based authentication with an OpenID Provider. Encountering challenges while attempting to write test cases for the program. The application runs smoothly from node CLI, obtaining the code and toke ...

Is there a way to trigger the ngOnInit() function in Angular 2 for a second time

I need help understanding how to re-trigger the ngOnInit() function when calling another method. Can you provide guidance on this in the following code snippet? ngOnInit(): void { this.route.params.subscribe((params: Params) => { this.model = th ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

How can I set up BaconJS in conjunction with Webpack and CoffeeScript?

Currently in the process of transitioning old code to Webpack and encountering some issues... Utilizing a dependency loader in TypeScript import "baconjs/dist/Bacon.js" And a module in CoffeeScript @stream = new Bacon.Bus() Upon running the code, I en ...

Filter the output from a function that has the ability to produce a Promise returning a boolean value or a

I can't help but wonder if anyone has encountered this issue before. Prior to this, my EventHandler structure looked like: export interface EventHandler { name: string; canHandleEvent(event: EventEntity): boolean; handleEvent(event: EventEntity ...

Oops! Looks like there was an issue with assigning to a reference or variable: Error: Uncaught (in promise)

I seem to be struggling with an issue that I believe may have been addressed before, but after reviewing other solutions, I am unable to pinpoint the error in my code. Any assistance in identifying my mistake would be greatly appreciated. <div class="j ...

Sending information from one Angular 2 component to another

As a newcomer to Angular 2, I am still in the process of understanding its functionalities. Currently, I have two components: 1) List Component This component is responsible for displaying all the products in a store and performing various functions. @C ...

Show JSON information in an angular-data-table

I am trying to showcase the following JSON dataset within an angular-data-table {"_links":{"self":[{"href":"http://uni/api/v1/cycle1"},{"href":"http://uni/api/v1/cycle2"},{"href":"http://uni/api/v1/cycle3"}]}} This is what I have written so far in my cod ...

What's the method for validating the spread operator in Typescript?

Is it possible to prevent this code from compiling? (since it currently does...) const bar: { a: string } = { a: '', ...{b: ''} } ...