arn-arn
arn-arn

Reputation: 1377

How to pass a html element property/attribute in the event handler in Angular 2?

I have a list of data which i display in the html template this way.

<div>
   <a (click)='onClick(this)' someproperty='test'></a>
   <a (click)='onClick(this)' someproperty='test'></a>
   <a (click)='onClick(this)' someproperty='test'></a>
   <a (click)='onClick(this)' someproperty='test'></a>
</div>

I want to change one property dynamically whenever i click an item. However, Angular is showing the object as undefined.

here is my Component:

declare var $:any;
export class MyComponent {
  onClick(someobject): void {
    $(someobject).attr('someproperty','dontTest');//console shows "Undefined"

  }
}

Upvotes: 3

Views: 7244

Answers (2)

No&#233;mi Sala&#252;n
No&#233;mi Sala&#252;n

Reputation: 5026

You can do it all by template

See Attribute Binding documentation.

<div>
   <a (click)="val1 = 'new val 1'" [attr.someproperty]="val1">Link 1</a>
   <a (click)="val2 = 'new val 2'" [attr.someproperty]="val2">Link 2</a>
   <a (click)="val3 = 'new val 3'" [attr.someproperty]="val3">Link 3</a>
</div>

Here the plunker

Just inspect the links and click on it to see someproperty changing.

Upvotes: 4

Madhu Ranjan
Madhu Ranjan

Reputation: 17894

try below,

 <a (click)='onClick($event)' someproperty='test'>click me</a>

 onClick(someobject): void {
    someobject.target.attributes['someproperty'].value = "donttest";
    console.log(someobject.target.attributes['someproperty'].value);
  }

Here is the Plunker!!

Hope this helps!!

Upvotes: 8

Related Questions