Raspberry Lemon
Raspberry Lemon

Reputation: 113

How to call a function on clicking a text in angular 8

I have an anchor tag in HTML. I want to create a click event which calls function. The issue is whatever solution I have tried makes the page reload. I don't want the page to reload or refresh.

  <div *ngIf="showOTPResendText">
    <p style="text-align: center;">Please wait {{counter | formatTime}} seconds(s) before requesting a new One Time Password(OTP)</p>
  </div>

  <div class="otp-not-recieved">
    <br />
    <h4>
      Not received your code?&nbsp;&nbsp;
      <a [routerLink]="/"></a>
      <a href="" onclick="resendOTP()"> Resend OTP.</a>

    </h4>
  </div>

The text looks something like this. Text Screenshot.

I want it to be text and still hit a function in typescript which calls the resend otp function.

What I have tried and problem I am facing with the solution.

  1. onclick="return false; It doesn't reload the page but then I can't call the function.
  2. Thought of using routerlink but then I don't want to route anywhere and if I route to same page it still reloads the page.

Upvotes: 1

Views: 4796

Answers (1)

Nicolas Gehlert
Nicolas Gehlert

Reputation: 3273

so if you want to have a click event but not go anywhere you can also just not use an <a> tag but regular <p>/<span>/... tag as well.

The angular way is to use the click attribute, so something like

<span (click)="callToYourFunction()">Text</span>

If you really want to use an <a> tag I think you should be able to prevent the event default. For example

<a (click)="myFunction($event)">Link</a>

function myFunction(event) {
    event.preventDefault();
}

Upvotes: 1

Related Questions