【问题标题】:How can I conditionally use either [href] or [routerLink] on an anchor?如何有条件地在锚点上使用 [href] 或 [routerLink]?
【发布时间】:2017-11-10 23:08:58
【问题描述】:

我需要在本地或外部资源有条件地指向相同的锚链接。我试过了

<a [href]="outside?externalUrl:null"  [routerLink]="outside?[]:['/route',id]" >test</a>

但它不起作用。我没有收到任何错误,但它指向同一个本地页面并忽略外部 URL。有什么想法吗?

另一种选择是构建链接,但我找不到任何文档如何在服务中访问 routerLink

编辑:我知道我可以使用*ngIf 克隆整个链接,但我不想这样做,我的链接包含一个带有很多选项的视频标签

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    最简单的方法是使用*ngIf / else:

    <ng-container *ngIf="outside; else internalBlock">
      <a [href]="externalUrl">External</a>
    </ng-container>
    
    <ng-template #internalBlock>
      <a [routerLink]="['/route', id]">Internal</a>
    </ng-template>
    

    EDIT#1:(丑陋的解决方法)

    既然你不想使用*ngIf(我还是不明白为什么),你可以这样做:

    模板:

    <a href="javascript:void(0)" (click)="handleClick(outside, '/route', id, externalUrl)">Link</a>
    

    组件:

    handleClick(outside: boolean, internalUrl: string, internalId: string, externalUrl: string): void {
      if (outside) {
        window.location.href = externalUrl;
        // You can also use Location class of Angular
      } else {
        this.router.navigate([`${internalUrl}/${internalId}`]);
      }
    }
    

    【讨论】:

    • @isherwood &lt;ng-container&gt; 和 &lt;ng-template&gt; 永远不会添加到浏览器中的 DOM 中,它们在浏览器看到之前由 Angular 处理。我不明白你的评论是什么意思。为什么你认为一个列表项会成为一个单独的列表?这个问题也没有说明任何关于列表的内容。
    • 示例代码不起作用, 应该放在 之外
    • @Zealitude ops,我的错。谢谢,我已经修好了。
    • @Toolkit:为什么会搞砸路由器?
    【解决方案2】:

    对于条件 href,在 attr 之前。在 href 为我工作之前使用 null 作为值,如下所示:

    [attr.href]="!item.subMenu ? item.url : null"
    

    【讨论】:

    • 对于某些用例,这是完美的解决方案。如果您的 a-tag 围绕整个元素,例如使用 *ngIf,您将需要重复整个子元素。只有在某些情况下 a-tag 需要链接到某些东西时,此解决方案才能防止这种情况发生。
    【解决方案3】:

    您可以通过在指令中注入RouterLinkWithHref 来访问routerLink 实例。

    指令:

    import { ElementRef, Optional, Input, Directive, OnChanges } from '@angular/core';
    import { RouterLinkWithHref } from '@angular/router';
    
    @Directive({
      selector: '[externalLink]'
    })
    export class ExternalLinkDirective implements OnChanges {
    
      @Input() externalLink: string;
    
      constructor(
        private el: ElementRef,
        @Optional() private link: RouterLinkWithHref
      ) {}
    
      ngOnChanges(){
    
        if (!this.link || !this.externalLink) {
          return;
        }
        this.el.nativeElement.href=this.link.href=this.externalLink;
    
        // Replace onClick
        this.link.onClick = (...args: any[]) => {
          return true;
        }
    
      }
    
    }
    

    用法:

    <!-- Ignore router link and use external link -->
    <a routerLink="/some/path" externalLink="https://google.com">Link</a>
    

    【讨论】:

    • 这不会仍然调用路由器事件吗?另一个问题,当链接只是静态链接时,为什么在这种情况下使用ngOnChanges?
    【解决方案4】:

    经过大量调查,我针对这个问题采用了不同的方法,因为我的&lt;a href&gt;...&lt;/a&gt;包含代码(例如可点击的 div)。例如,我不想使用ngIf,因为这迫使我复制 div 的内部代码。所以这是我的解决方案:

    组件 HTML

    <div>
       <a [href]="getRouterLink()" >
         <div class="section">
         <!-- stuff inside the div -->
         </div>   
       </a>
    </div>
    

    组件 JS

    Component({
    selector: 'app-home-section',
    templateUrl: './home-section.component.html',
    styleUrls: ['./home-section.component.scss']
    })
    export class HomeSectionComponent implements OnInit {
    
    @Input() link: string;
    
    constructor(private router: Router) { }
    
    ngOnInit() {
    }
    
    isRouterLink() {
    
      if (this.link) {
        let firstLinkChar = this.link.charAt(0);
        let isSlash = firstLinkChar == '/';
        return isSlash;
      }
    
      return false;
    }
    
    getRouterLink() {
    
      let url = this.isRouterLink() ? window.location.origin + this.link : 'http://' + this.link;  
    return url;
     }
    }
    

    这是使它工作更简单的唯一方法,因为即使我将“www.example.com”直接放到href(有或没有[ ]),它总是附加基本网址。它不漂亮,但很实用。

    【讨论】:

    • 这不是仍然使用href 属性。 routerLink 和 href 之间存在细微差别。你可以阅读它here
    【解决方案5】:

    对于我的用例,&lt;a&gt; 标签内的内容中有一些嵌套的 html,因此我必须为此创建一个自定义组件。

    组件的作用基本上是

    • 使用内容嵌入
    • 在上下文中使用ngTemplateOutlet
    • 有条件地显示带有routerLink 指令或href 的&lt;a&gt; 标记。

    • route-or-redirect.component.ts
    import {
      Component,
      ContentChild,
      Directive,
      Input,
      OnInit,
      TemplateRef,
    } from '@angular/core';
    import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
    
    export interface Bookmark {
      id: string;
      title: string;
      imgUrl: string;
    }
    
    @Directive({
      selector: '[appLinkContent]',
    })
    export class RouteOrRedirectLinkContentDirective {}
    
    @Component({
      selector: 'app-router-or-redirect',
      templateUrl: './router-or-redirect.component.html',
      styleUrls: ['./router-or-redirect.component.scss'],
    })
    export class RouteOrRedirectComponent implements OnInit {
      @Input() route = '/';
      @Input() set externalLink(link: string) {
        this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(link);
      }
      @Input() redirect = false;
      @Input() bookmark!: Bookmark;
      @ContentChild(RouteOrRedirectLinkContentDirective, { read: TemplateRef })
      linkContent: TemplateRef<RouteOrRedirectLinkContentDirective> | undefined;
    
      safeUrl: SafeResourceUrl | undefined;
    
      constructor(private sanitizer: DomSanitizer) {}
    
      ngOnInit(): void {}
    }
    
    • route-or-redirect.component.html
    <a [routerLink]="route" *ngIf="!redirect; else redirectLink">
      <ng-container
        *ngTemplateOutlet="linkContent; context: { $implicit: bookmark }"
      ></ng-container>
    </a>
    
    <ng-template #redirectLink>
      <a [attr.href]="safeUrl">
        <ng-container
          *ngTemplateOutlet="linkContent; context: { $implicit: bookmark }"
        ></ng-container>
      </a>
    </ng-template>
    
    • route-or-redirect.component.ts
    import { Component, OnInit, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { By } from '@angular/platform-browser';
    import { RouterLinkWithHref, RouterModule } from '@angular/router';
    import { RouterTestingModule } from '@angular/router/testing';
    
    import {
      Bookmark,
      RouteOrRedirectComponent,
      RouteOrRedirectLinkContentDirective,
    } from './router-or-redirect.component';
    
    @Component({
      selector: 'app-test',
      template: `
        <app-router-or-redirect class="default-no-content"></app-router-or-redirect>
    
        <app-router-or-redirect class="default-with-content">
          <div *appLinkContent>test link</div>
        </app-router-or-redirect>
    
        <app-router-or-redirect
          class="use-route"
          route="/test"
          externalLink="localhost:4200"
        >
          <div *appLinkContent>test link</div>
        </app-router-or-redirect>
    
        <app-router-or-redirect
          class="use-redirect"
          route="/test"
          externalLink="localhost:4200"
          [redirect]="true"
        >
          <div *appLinkContent>test link</div>
        </app-router-or-redirect>
    
        <app-router-or-redirect
          class="link-with-context"
          route="/test"
          externalLink="localhost:4200"
          [redirect]="true"
          [bookmark]="bookmark"
        >
          <div *appLinkContent="let bookmark">
            <img [attr.src]="bookmark.imgUrl" />
            <h3>{{ bookmark.title }}</h3>
          </div>
        </app-router-or-redirect>
      `,
      styles: [],
    })
    export class TestRouterOrRedirectComponent implements OnInit {
      bookmark: Bookmark = {
        id: '1',
        title: 'Test Link',
        imgUrl: 'https://placeimg.com/640/480/any',
      };
    
      constructor() {}
    
      ngOnInit(): void {}
    }
    
    describe('RouterOrRedirectComponent', () => {
      let component: TestRouterOrRedirectComponent;
      let fixture: ComponentFixture<TestRouterOrRedirectComponent>;
    
      let defaultWithNoContent: RouteOrRedirectComponent;
      let defaultWithContent: RouteOrRedirectComponent;
      let useRoute: RouteOrRedirectComponent;
      let useRedirect: RouteOrRedirectComponent;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
          imports: [RouterModule, RouterTestingModule],
          declarations: [
            TestRouterOrRedirectComponent,
            RouteOrRedirectComponent,
            RouteOrRedirectLinkContentDirective,
          ],
        }).compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(TestRouterOrRedirectComponent);
        component = fixture.componentInstance;
    
        defaultWithNoContent = fixture.debugElement.children[0].componentInstance;
        defaultWithContent = fixture.debugElement.children[1].componentInstance;
        useRoute = fixture.debugElement.children[2].componentInstance;
        useRedirect = fixture.debugElement.children[3].componentInstance;
    
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    
      it('should default to link with route point to /', () => {
        const link = fixture.debugElement
          .query(By.css('.default-no-content'))
          .query(By.directive(RouterLinkWithHref));
    
        expect(link).toBeTruthy();
        expect(link.attributes.href).toBe('/');
      });
    
      it('should default to link with content and route points to /', () => {
        const link = fixture.debugElement
          .query(By.css('.default-with-content'))
          .query(By.directive(RouterLinkWithHref));
    
        expect(link.attributes.href).toBe('/');
        expect(link.nativeElement.textContent).toBe('test link');
      });
    
      it('should use routerLink for <a> tag if "redirect" binding is not specified', () => {
        const link = fixture.debugElement
          .query(By.css('.use-route'))
          .query(By.directive(RouterLinkWithHref));
    
        expect(link.attributes.href).toBe('/test');
        expect(link.nativeElement.textContent).toBe('test link');
      });
    
      it('should default "redirect" binding to false', () => {
        expect(useRoute.redirect).toBe(false);
      });
    
      it('should use href for <a> tag if "redirect" is true', () => {
        const link = fixture.debugElement
          .query(By.css('.use-redirect'))
          .query(By.css('a'));
    
        expect(useRedirect.redirect).toBe(true);
        expect(link.query(By.directive(RouterLinkWithHref))).toBeNull();
    
        expect(link.nativeElement.href).toBe('localhost:4200');
        expect(link.nativeElement.textContent).toBe('test link');
        expect(useRoute.redirect).toBe(false);
      });
    
      it('should use the bound value as the link template context', () => {
        const link = fixture.debugElement
          .query(By.css('.link-with-context'))
          .query(By.css('a'));
    
        expect(link.query(By.css('h3')).nativeElement.textContent).toContain(
          component.bookmark.title
        );
        expect(
          link.query(By.css('img')).nativeElement.getAttribute('src')
        ).toContain(component.bookmark.imgUrl);
        expect(useRoute.redirect).toBe(false);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 2018-06-30
      • 2022-12-10
      • 2021-05-01
      • 1970-01-01
      相关资源
      最近更新 更多