JensB
JensB

Reputation: 6850

Disable <a> tag in Angular conditionally

I'm trying to disable a link in an Angular template. May be asking an impossible question. Is it possible to do something like this?

<a [routerLink]="['/details', item.id]" [disable]="disable">
    <div class="row">
        <div class="col-12">
        <h4>text text text</h4>  
        </div>
    </div>
</a>

When the link is disabled I want it to behave <a> tag is just as a regular <div>.

Upvotes: 2

Views: 7827

Answers (5)

Yogendra Chauhan
Yogendra Chauhan

Reputation: 825

You can write it like this:

<a [routerLink]="disable ? null : ['/details', item.id]" [class.disabled]="disable">
    <div class="row">
        <div class="col-12">
        <h4>text text text</h4>  
        </div>
    </div>
</a>

.disabled {
    pointer-events: none;
}

Upvotes: 0

Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5041

Try the below code. Change href value based on the condition and apply some styles

Working stackblitz

Template

<a [routerLink]="disable ? null : ['/details', 1]" [ngClass]="{'anchor-disable' : disable}">
  <div class="row">
    <div class="col-12">
      <h4>text text text</h4>
    </div>
  </div>
</a>

CSS

a.anchor-disable {
  color: black;
  cursor: text;
  pointer-events: none;
  text-decoration: none;
}

Upvotes: 3

Vna
Vna

Reputation: 542

If you are using angular material, you can use mat-button property and ngClass to achieve this

<a mat-button href="https://www.google.com/" target="_blank" disabled="{{isDisabled}}"
    [ngClass]="{'simple-text': isDisabled}">
    Sample link
</a>

css

.simple-text {
  color: black !important;
}

stackblitz demo: https://stackblitz.com/edit/angular-hkmkn9?file=src%2Fapp%2Fapp.component.css

Upvotes: 0

Alex G.
Alex G.

Reputation: 127

If the content of your a-tag is that complex, then just outsource it in its own component or into ng-template, so you can put it into the a-tag and the div without it being a huge mess. I don't think conditionally replacing the a-tag with a div as you would like to do is possible.

Upvotes: 0

Shri Hari L
Shri Hari L

Reputation: 4894

I would try to give you an idea.
Can we do something like this?

<div *ngIf="condition; else elseBlock">
    <div class="row">
      <div class="col-12">
        <h4>text text text</h4>  
      </div>
    </div>
</div>
<ng-template #elseBlock>
<a [routerLink]="['/details', item.id]">
    <div class="row">
      <div class="col-12">
        <h4>text text text</h4>  
      </div>
    </div>
</a>
</ng-template>

Upvotes: 0

Related Questions