cdh429
cdh429

Reputation: 357

Accessing the HTML Button ID in TS file (Ionic)

I'm looking to call the HTML button ID into my TS file. I know it's not best practice to use "getElementByID" (or so I've read) in Ionic. Was wondering what the appropriate approach would be.

Here is my Code...

HTML

<button id="B" value="{{gamer[indexCount].correct}}" ion-button class="answerButtona" block (click)="answerClicked('B')">
    {{gamer[indexCount].B}}
  </button>

TS

answerClicked(ans){
//this is my function now
}


let body = {
    user_id: this.gamer[this.indexCount]['ID'],
    userAnswer: **Looking to call ans here**
}

I'm now passing in a parameter to the function. How would I access the parameter. this.ans doesn't seem to be working.

EDIT: Update to the code

Upvotes: 0

Views: 4807

Answers (2)

Mahesh Jadhav
Mahesh Jadhav

Reputation: 1089

The best approach to get access to Dom elements in angular(ionic) would be by using @ViewChild

You can use a reference to target that specific element like this:

<div #myElement></div>

inside you ts now you can have access to that element using these imports and the @ViewChild:

import {ElementRef, ViewChild} from '@angular/core';

@ViewChild('myElement') myElement: ElementRef;

constructor(){

}

and then access it like this :

ngAfterViewInit() {
  console.log(this.myElement.nativeElement);
}

Upvotes: 2

DavidX
DavidX

Reputation: 1319

One approach is to make answerClickedB() set something like this.userAnswer = 'B' and then use this.userAnswer.

Or even better:

(click)=`answerClicked('B')` in the HTML

and this in the .ts

answerClicked(ans) {
    this.userAnswer = ans;
}

You're right that your approach is not the 'ionic' way. The 'ionic' way or 'angular' way is to use bindings, not gets on DOM elements.

Upvotes: 2

Related Questions