0

I have something like the following code in my template

<button class="btn" >
  <audio src="mySourceFile.wav"></audio>
</button>

on Click I want to play the audio Object. So what I'd like is something like

<button class="btn" (click)="this.audio.play()">

or maybe

<button class="btn" (click)="self.firstElementChild.play()">

The button is part of a loop so I'm trying to avoid having to use the id I just want the audo object that's a child of the current button. Also, I really want to send it to a function rather than actually play it directly. So the actual code would be more like.

<button *ngFor="let item of object | keyvalue" 
         class="btn" 
         id={{item.key}}
         (click)="myFunction(self.firstElementChild)"
  ><audio src={{item.value}}></audio>
</button>

Only so far as I have been able to tell there doesn't seem to be a way to access a DOM node as "self" or "this". I'm very much hoping I'm just missing something and there is a way to access without using dynamic ids.

cparrish817
  • 351
  • 4
  • 10
  • `self` refers to the current window. You want `this.firstElementChild`. Or, use the event passed in by Angular as in [Angular2 get clicked element id](https://stackoverflow.com/q/36006894/215552) – Heretic Monkey Mar 15 '20 at 22:17
  • thank you if you put this as an answer I'll mark it as such. – cparrish817 Mar 15 '20 at 23:01

1 Answers1

0

So what is working for me. In my template

<button *ngFor="let item of object | keyvalue" 
         class="btn" 
         id={{item.key}}
         (click)="myFunction($event)"
  ><audio src={{item.value}}></audio>
</button>

In my component

 myFunction(event: Event){
    let audio = (event.target as Element).firstElementChild as HTMLAudioElement;
    audio.play();
  }
cparrish817
  • 351
  • 4
  • 10