Home > Blockchain >  How to change title attribute inside a tag when clicked with Angular?
How to change title attribute inside a tag when clicked with Angular?

Time:07-22

I'm trying to change the title attribute inside an tag when clicked. If you click it again the title attribute should change it back to its initial state and so it goes. I can make the change of the title happen, but I'm having trouble making it go back to its initial state when clicked again. Here's the code:

HTML
<a title="1" id="initial" role="button" (click)="magic()">
<p>test</p>
</a>

TS

magic(): void {
    document.getElementById("initial")?.setAttribute("title", "2");
  }

CodePudding user response:

To do that you need to store somewhere a default value of the title and then toggle it on click.

For example you can have defaultTitle property in your class, and then when you need to switch back to a default value you can just reuse that property:

TS

private defaultTitle = 'default-value';
title = this.defaultTitle; 

magic(): void {
  if (this.title === this.defaultTitle) {
    this.title = 'new-value';
  } else {
    this.title = this.defaultTitle;
  }
}

HTML

<a [title]="title" id="initial" role="button" (click)="magic()">
  <p>test</p>
</a>

CodePudding user response:

You can use angular binding with a variable.

HTML

<a [title]="title" id="initial" role="button" (click)="magic()">
  <p>test</p>
</a>

or

<a title="{{title}}" id="initial" role="button" (click)="magic()">
  <p>test</p>
</a>

TS

title = 1;
magic(): void {
  this.title = 1   this.title % 2;
}
  • Related