同一页面上页面其他部分的 Angular 17 独立链接

问题描述 投票:0回答:1

这是我定义链接的地方

<div class="form-column">
            <a href="#" (click)="scrollTo('form-container')" class="heading"
              >Book a Clarity Call</a
            >
          </div>

这是我定义id的地方

 <div class="post-card-container" id="form-container">

以下是我在组件内的函数

import { Cimport { Component, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
  selector: 'app-contact-us',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './contact-us.component.html',
  styleUrl: './contact-us.component.scss',
})
export class ContactUsComponent {
constructor(private elementRef: ElementRef) {}
scrollTo(elementId: string): void {
    const element = document.getElementById(elementId);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }
}

我尝试将组件模板的一部分用作链接,单击该链接后,它必须将我带到模板中 id 所在的部分,但不起作用。

html typescript href anchor angular17
1个回答
0
投票

你的scrollTo方法有很多代码

只需将其更改为:

scrollTo(elementId: string) {
  window.location.hash = elementId;
}
© www.soinside.com 2019 - 2024. All rights reserved.