如何滚动查看 Angular 11 中的动态加载内容?

问题描述

在我的应用程序中,我需要从文件加载 HTML。该文件包含纯 HTML 代码和锚点。现在,当我单击这样的锚点时,我想将此锚点滚动到视图中。因此我写了以下代码

HTML 代码

<div class="section">
    <a href="#distancegroup">distanceGroup</a>
</div>

...

<h3 id="distancegroup">distancegroup</h3>

组件

@Component({
    selector: 'loadHTMLContent',template: `<span [innerHTML]="content"></span>`,})
export class LoadHTMLContentComponent implements OnInit {
    @Input('file') file: string;
    public content: any;

    constructor(private http: HttpClient,private sanitizer: DomSanitizer,private ref: ElementRef) {}

    ngOnInit() {
        if (!this.file) return;

        this.http.get(this.file,{ responseType: 'text' }).subscribe(response => {
            this.content = this.sanitizer.bypassSecurityTrustHtml(response);
        });
    }

    ngAfterViewInit() {
        setTimeout(() => {
            const anchors = [...this.ref.nativeElement.querySelectorAll('a')];
            anchors.forEach(a =>
                a.addEventListener('click',e => {
                    e.preventDefault();
                    a.scrollIntoView({ behavior: 'smooth',block: 'center' });
                })
            );
        },1000);
    }
}

现在的问题是 scrollIntoView 不起作用,我真的不知道我的代码有什么问题。请问有人有想法或解决方案吗?

或者是否有可能从 HTML 字符串创建一个真正的 Angular 组件,以便也可以使用路由器?

解决方法

我认为您正在尝试将锚点而不是目标元素滚动到视图中。所以试着像这样改变(见我的类似例子 here):

anchors.forEach(a =>
  a.addEventListener("click",e => {
    const el = this.ref.nativeElement.querySelector(a.getAttribute('href'));

    e.preventDefault();
    el.scrollIntoView({ behavior: "smooth",block: "center" });
  })
);