如何使用Angular 9实现滚动到指定div元素内容底部的功能
实现方案
步骤1:给进度条容器添加模板引用变量
方便Angular定位对应DOM元素,模板代码修改如下:
<div #progressBar *ngIf="formSubmitted"> <img src="assets/progressbar.gif"> </div>
步骤2:组件内获取元素引用并触发滚动
有两种可选实现方式,都可以满足需求:
方式1:用setTimeout等待DOM渲染完成
import { Component, ViewChild, ElementRef } from '@angular/core'; @Component({ // 保留你原有的组件配置 }) export class 你的组件名 { formSubmitted = false; // 获取进度条元素引用,static设为false因为是*ngIf动态渲染的元素 @ViewChild('progressBar', { static: false }) progressBar: ElementRef<HTMLElement>; 表单提交方法() { this.formSubmitted = true; // 延迟0ms执行,等Angular完成动态DOM渲染 setTimeout(() => { if (this.progressBar?.nativeElement) { this.progressBar.nativeElement.scrollIntoView({ behavior: 'smooth', // 不需要平滑滚动可以改成'auto' block: 'end' // 滚动对齐到元素底部,符合你的需求 }); } }, 0); // 保留你原有的HTTP请求提交逻辑 } }
方式2:手动触发变更检测(更规范的Angular写法)
不想用setTimeout的话可以注入变更检测器,手动触发DOM更新后直接滚动:
import { Component, ViewChild, ElementRef, ChangeDetectorRef } from '@angular/core'; @Component({ // 原有组件配置 }) export class 你的组件名 { formSubmitted = false; @ViewChild('progressBar', { static: false }) progressBar: ElementRef<HTMLElement>; constructor(private cdr: ChangeDetectorRef) {} 表单提交方法() { this.formSubmitted = true; // 手动触发变更检测,立即渲染进度条节点 this.cdr.detectChanges(); if (this.progressBar?.nativeElement) { this.progressBar.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end' }); } // 原有HTTP请求提交逻辑 } }
内容的提问来源于stack exchange,提问作者Joel Menezes
相关产品推荐
相关产品推荐

