首页 > 解决方案 > 在 Angular 9 中使用内部链接

问题描述

编辑:我在同一个组件中使用 href 和带有 id 的部分滚动到指定 id 的 div。

我做了一个简单的 href="contato" 和一个 id="contato" 的部分并且可以工作,但是......我想知道如何在没有错误“未捕获(承诺)的情况下做到这一点:错误:无法匹配任何路线. URL 段:'contato' 错误:无法匹配任何路由。URL 段:'contato'”在控制台上!

  <span class="nav-list" id="nav-list">
        <div fxFlex fxShow="true" fxHide.sm="true"></div>
            <a href="#inicio" class="nav-list-menu" alt="home">
                Home
            </a>
            <a href="#recursos" class="nav-list-menu" alt="Recursos">
                Recursos
            </a>
            <a href="#contato" class="nav-list-menu" alt="Contato">
                Contato
            </a>
            <a (click)="this.login()" class="nav-list-menu enter-button"  alt="Entrar no sistema">
                Entrar
            </a>
    </span>


<section id="recursos" style="width: 100%; height: 40px; background-color: white;"></section>

标签: htmlangular

解决方案


你可以这样做

document.getElementById('id').scrollIntoView();

注意在提供 ID 时不要使用 # 作为前缀

一个例子就像

element.scrollIntoView();
element.scrollIntoView(alignToTop); // Boolean parameter
element.scrollIntoView(scrollIntoViewOptions); // Object parameter


var element = document.getElementById("box");

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});

您可以通过这种方式以角度访问组件

import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';

@Component({
    selector: 'app',
    template: `
        <div #myDiv>Some text</div>
    `,
})
export class AppComponent implements AfterViewInit {
    @ViewChild('myDiv') myDiv: ElementRef;

    ngAfterViewInit() {
        console.log(this.myDiv.nativeElement.innerHTML);
    }
}

Mozilla 中有一个简短的文档

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

如果你的作品完成了,请检查它如果它有效,请投票并批准..!!


推荐阅读