简体   繁体   中英

Angular: How to override nested href with routerLink?

I have a third-party package that is using an href attribute on a nested anchor tag. Of course, I don't want to navigate using href . I applied a routerLink directive on the parent because I have no way of accessing and modifying the child component. But the href attribute overrides everything. How can I force angular to use the routerLink directive?

My code looks like this:

<ngx-gallery routerLink="home" [options]="galleryOptions" [images]="galleryImages"></ngx-gallery>

First of all, in the source code and documentation from ngx-gallery I can't find any reference of an anchor tag being set, but if you say there is, I should believe you.

You can however try to manually remove the href value from the anchor tag. You can even write a separate directive for it:

@Directive({
  selector: '[disableLinks]'
})
export class DisableLinksDirective implements AfterViewInit, OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  constructor(
    private el: ElementRef<HTMLElement>
    @Optional() @Self() private gallery: NgxGalleryComponent
  ) {}

  ngOnInit(): void {
    if (this.gallery) {
      merge(
        this.gallery.imagesReady,
        this.gallery.change,
        this.gallery.previewChange
      ).pipe(
        takeUntil(this.destroy$)
      ).subscribe(() => this.disableLinks())
    }
  }

  ngAfterViewInit(): void {
    this.disableLinks();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  private disableLinks(): void {
    this.el.nativeElement.querySelectorAll('a').forEach((a) => a.href = '');
  }
}

Which you can then set on your element:

<ngx-gallery
  disableLinks
  routerLink="home"
  [options]="galleryOptions"
  [images]="galleryImages">
</ngx-gallery>

I don't exactly know if any of those events will trigger the href to be updated again, but that's for you to find out:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM