Home > database >  How to disable the anchor tag in angular only for the first component?
How to disable the anchor tag in angular only for the first component?

Time:11-22

I'm working on an Angular application, and I want to disable an HTML element only when the form is on its first page. What is the correct way to do this?

The HTML Code:

<div style="float: left">
      <a (click)="mActive(false)" >&laquo; Previous </a>
    </div>
    <div style="float: right">
      <a (click)="mActive(true)" >Next &raquo;</a>
    </div>

The TypeScript Code:

active_flag = 0;
  max_list = 4;
  mActive(arg: any) {


    if (arg) {
      this.active_flag = (this.active_flag < this.max_list) ? this.active_flag   1 : this.active_flag;
    } else {
      this.active_flag = (this.active_flag > 0) ? this.active_flag - 1 : this.active_flag;
    }
  }

Now, I want to disable the Previous tag only for first component and i need to disable the Next tag for the last component of the form.

I need to actually prevent the element from being clickable, not just appear that it is with the CSS. I was assuming that I needed to potentially bind to the [disabled] attribute at first, but this is incorrect as the anchor element doesn't have a disabled property.

I looked at and considered using the pointer-events: none but this prevents my style of cursor: not-allowed from working -- and this is part of the requirement.

CodePudding user response:

Generally you has a variable that store the actual page (e.g. called "page"). Always it's better that the page goes from 0 to number of pages-1. Then simply

<a [class.disable]="page==0" (click)="page!=0 && dosomething()">prev</a>. 

See that the a has a class "disabled" when page==0 and only execute the function if page!=0. It's typical the construction (click)="condition && function()": if the condition it's not fulfilled, the function it's not executed

For the next you has a variable "num_pages" (it's better than it be really the number of pages-1)

<a [class.disable]="page>=num_pages" 
      (click)="page<num_pages && dosomething()">next</a>. 

And your page

{{page 1}}

NOTE: the pages goes from 0 to num_pages-1 because you can use, e.g. |slice:(page*itemsXPage):(page*itemsXPage itemsXPage)

  • Related