All files / skip-links si-skip-link-target.directive.ts

100% Statements 8/8
100% Branches 0/0
100% Functions 3/3
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42                                1x       28x   28x 28x     28x       28x             1x 1x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { Directive, ElementRef, inject, input, OnDestroy, OnInit } from '@angular/core';
import { TranslatableString } from '@siemens/element-translate-ng/translate';
 
import { SkipLinkService } from './skip-link.service';
 
/**
 * Directive to mark an element as a target for a skip link.
 * If this directive is applied to a none interactive element, a tabindex of -1 must be added manually.
 */
@Directive({
  selector: '[siSkipLinkTarget]'
})
export class SiSkipLinkTargetDirective implements OnInit, OnDestroy {
  /**
   * The name of the skip link target which will be shown in the skip link.
   */
  readonly name = input.required<TranslatableString>({ alias: 'siSkipLinkTarget' });
 
  private skipLinkService = inject(SkipLinkService);
  private elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
 
  ngOnInit(): void {
    this.skipLinkService.registerLink(this);
  }
 
  ngOnDestroy(): void {
    this.skipLinkService.unregisterLink(this);
  }
 
  /**
   * Call this methode to "activate" a skip link target. It will focus this element and scroll it into the view.
   */
  jumpToThisTarget(): void {
    this.elementRef.nativeElement.scrollIntoView({ block: 'nearest', inline: 'nearest' });
    this.elementRef.nativeElement.focus();
  }
}