user4096537
user4096537

Reputation:

Angular - How to access the nativeElement in click handler

Maybe only a "stylish" but nonetheless...

I've the following which is working:

// Template
<div *ngFor="let media of period.media">
    .
    .
    .
    <button #btn (click)="onDeleteClick(btn)" [attr.media-id]="media.ID">
        {{'DELETE' | translate}}
    </button>
</div>

//component.ts
    this.period.media = [
        {id: 123}, {id: 456}, ...
    ];
    .
    .
    .
    onDeleteClick(elem) {
        console.log(elem._elementRef.nativeElement.getAttribute('media-id'));
    }

It works (the console shows 123, 456,...) but accessing the nativeElelement using the _elemntRef sounds like a hack (underscore denotes Private property, like _privateVar, isn't it).

So what would be a more elegant way to access the nativeElement or, even better, its 'media-id' attribute?

Thanks a lot for any hint.

EDIT

The answer to this question is in the comments from user184994 and JB Nizet. Since they both addressed the problem correctly I cannot set the "accepted answer" flag since it can be assigned to only once.

Therefore I'm editing my question as acknowledgement of this.

Upvotes: 0

Views: 1234

Answers (1)

v8-E
v8-E

Reputation: 1105

Answer is already given but I would like to add one more point and answer it. you're using button, for most browsers the default type of button is submit. and if try to delete it will get submitted,if you do not want it you can change it's type to type = "button" .

<div *ngFor="let media of period.media">
    <button type = "button" #btn 
  (click)="onDeleteClick(media)"
   [attr.media-id]="media.ID">{{'DELETE' | translate}}</button>
</div>

additionally if you want you can pass only id if you need or want, just use onDeleteClick(media.id) this is better in terms of performance. You can remove template varibale if you don not required it.
//component.ts

this.period.media = [
    {id: 123}, {id: 456}, ...
];
.
.
.
onDeleteClick(media) {
    console.log(media.id);
}

if you are passing only id then need to change syntax like

  onDeleteClick(id) {
        console.log(id);

    }

Upvotes: 1

Related Questions