This object does not have support for the attribute or method "getAttribute"

I've searched for solutions, but nothing seems to work for me and now I'm feeling quite lost. My current setup involves Cordova, Ionic, and Angular 2.

Below is the HTML snippet:

 <ion-col *ngFor="let value of myButtonsFirstRow" width-25>
  <button #elem ptcolor (click)="volumeClick(elem)" attr.floatValue="{{value}}">
    {{value | fraction}}
  </button>
</ion-col>

And this is my TypeScript code:

volumeClick(htmlElem: HTMLElement) {
  this.volumeSelected = +htmlElem.getAttribute('floatValue'); 
}

My aim is to retrieve the value from an attribute that I created in my HTML. However, it seems like I can't access the getAttribute method. Although the htmlElem variable is set, I am unable to see the method, and I know there's something wrong with what I'm doing, but I can't figure out what!

Any help would be greatly appreciated.

Answer №1

Absolutely, the reason for this behavior is that elem represents an Ionic component. There are several methods to achieve the desired outcome:

1) Regrettably, the Button component lacks a public method or property for accessing nativeElement or attribute. The following code should suffice:

volumeClick(elem: any) {
    this.volumeSelected = +elem._elementRef.nativeElement.getAttribute('floatValue'); 
}

2) Another approach is to retrieve the attribute using $event in your template like so:

<button (click)="volumeClick($event)" attr.floatValue="{{value}}"> {{value}}</button>

Your method would then appear as follows:

volumeClick(event: any) {
  this.volumeSelected = +event.currentTarget.getAttribute('floatValue'); 
}

PLEASE NOTE: I have used currentTarget because the Button component contains multiple children.

3) Alternatively, you can simply pass the value to the click event:

<button (click)="volumeClick(value)">{{value}}</button>

volumeClick(value: any) {
  this.volumeSelected = value; 
}

Or take a more straightforward approach:

<button (click)="volumeSelected = value">{{value}}</button>

Answer №2

When working with a template variable, you will receive an ElementRef as a reference. To interact with the actual HTMLElement, simply access it using ElementRef.nativeElement

handleClick(htmlElement: ElementRef) {
  this.selectedVolume = +htmlElement.nativeElement.getAttribute('floatValue'); 
}

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

The icon for caret down in FontAwesome is not displaying when using ngClass

I am experiencing an issue where only the fontawesome caret up is displayed when sorting a field, but the fontawesome caret down is not showing. I have provided the code snippet below. HTML <th (click)="sort('ref')">Ref {{reverse}} & ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Using NodeJS API gateway to transfer image files to S3 storage

I have been attempting to upload an image file to S3 through API Gateway. The process involves a POST method where the body accepts the image file using form-data. I crafted the lambda function in TypeScript utilizing the lambda-multipart-parser. While it ...

When working with Typescript, you can declare an interface and split its definition across multiple files

I've been developing a software application that utilizes WebSocket with the NodeJS ws package. My networking structure revolves around a module responsible for handling message reception and transmission. Given that I'm working with TypeScript, ...

Tips for dynamically loading a child component and passing data from the child component to the parent component

In my current setup, I have organized the components in such a way that a component named landing-home.component loads another component called client-registration-form.component using ViewContainerRef within an <ng-template>, and this rendering occu ...

Encountering an issue connecting to the backend server for the

I am attempting to make a POST request from my Angular 2 frontend to my Spring backend, but I am encountering an error. The error message: GET http://localhost:8080/loginPost 405 () Failed to load http://localhost:8080/loginPost: No 'Access-Control ...

Assuming control value accessor - redirecting attention

import { Component, Input, forwardRef, OnChanges } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'formatted-currency-input', templateUrl: '../v ...

The contents table remains fixed in the top right corner as you scroll

I have developed an Angular app with a table-of-contents component that only displays two items. The code for the script is as follows: ts import { Component, OnInit } from '@angular/core'; import { pdfDefaultOptions } from 'ngx-extended-p ...

Upon successfully logging into the app, Azure AD B2C integrated with MSAL and Angular will automatically redirect users to the login page

I recently updated my Angular app to make it accessible to customers by switching from ADAL to MSAL for authentication. I configured the app with Azure AD B2C credentials and everything seems to be working smoothly, except for one issue. When I try to logi ...

What is the best way to create a method that waits for a POST request to complete?

I have the following code snippet: login() { const body = JSON.stringify({ "usuario":"juanma", "password":"1234"}); console.log(body); let tokencito:string = '' const params = ne ...

At what point is the ngOnInit function invoked?

Here is the code snippet I am working with: <div *ngIf="hotels$ | async as hotels; else loadGif "> <div *ngFor="let hotel of hotels | hotelsFilter: _filteredType; first as f; index as i " appInit [hotel]="hotel " [first]="f "> < ...

What is the best way to retrieve a {collection object} from a JavaScript map?

My application utilizes a third-party library that returns the map in the following format: public sids: Map<SocketId, Set<Room>> = new Map(); When I try to access it using the code below: io.of("/").adapter.sids.forEach(function(va ...

Utilizing indexing for list data presentation in Angular instead of relying on property names

I need help with displaying data from a list retrieved from a database without having to specify the property names. I want to create reusable Markup for this purpose. Below is my current code snippet: <div class="card card-design" *ngFor="let val of l ...

What is the best way to track events in angular-meteor when a user logs in, logs out, or when there is a change in the user

I am working on meteor-angular and trying to track new user login and logout changes within a single component. I have attempted to subscribe to userData in the component's initialization, but it does not seem to detect when the user logs in or out. I ...

Is it possible to streamline the process of importing all CommonModule modules during bootstrap with the new standalone feature in Angular?

I've recently started experimenting with Angular's standalone feature and module-less approach. However, I'm having trouble finding the information I need. From what I understand, in a standalone component you have to import any directives/ ...

Using Typescript and JSX to render a component that has been passed as an argument

I am seeking to create a function that will render a React component passed as an argument. I aim to accommodate both Component and StatelessComponent types with the following approach: function renderComponent(component: React.ComponentClass<any> | ...

Exploring Angular 2: Unlocking the Power of Directives within Components

To display a dialog component on the main component page after clicking a button, I used directives in the following way: Within the template: <button id="goToTasksCases" class="btn btn-success btn-lg" (click)="doShowStartNewCase($event)">START A N ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

Determine the type of a function to assign to the parent object's property

Consider the following scenario: class SomeClass { public someProperty; public someMethodA(): void { this.someProperty = this.someMethodB() } public someMethodB() { ...some code... } } I need the type of somePropert ...