Conditionally add RouterLink or other attribute directives to an element in Angular 2

后端 未结 5 952
孤独总比滥情好
孤独总比滥情好 2020-12-29 18:15

In Angular 2 if I have an element like how can I conditionally add an attribute directive like [routerLink]=\"[\'SomeRoute\'

相关标签:
5条回答
  • 2020-12-29 18:23

    Just a detail. Try to avoid using buttons for navigation. Screenreaders wont understand that its a navigation out of the box. You will now need to add an aria-label that tells the screenreaders what it does. This adds more code. But the simple solution would be to add the [routerLink] to an anchor link. Then style it as a button. But I prefer to use the standard blue links because people usually knows what will happen then. ex: I would never try to rightclick on a button and open it in a new tab. So: buttons for operations and anchorlinks for navigation

    0 讨论(0)
  • 2020-12-29 18:25

    Or you can simply add a condition to the attribute.

    <button [routerLink]="myVar ? ['/myScreen'] : []"></button>
    

    Redirect to '/myScreen' only if myVar is true.

    0 讨论(0)
  • 2020-12-29 18:25

    If you don't want to duplicate the element, and just want to prevent clicks depending on the condition, you could do the following:

    <button 
      [style.pointer-events]="condition ? 'auto' : 'none'" 
      routerLink="/some/route"
    >
    </button>
    
    0 讨论(0)
  • 2020-12-29 18:33
       <div [ngClass] ='{"disabled-link":!isMicrositeEnable,"cursor-pointer":"isMicrositeEnable"}' [routerLink]="isMicrositeEnable ? ['/microsite'] : []">
    
    0 讨论(0)
  • 2020-12-29 18:36

    As far as I know, there is no straight way to do this. There are some workarounds... I used something like this:

    <button *ngIf="condition" [routerLink]="['SomeRoute']"></button>
    <button *ngIf="!condition"></button>
    

    There is an similar discussion here: link

    0 讨论(0)
提交回复
热议问题