1、HTML代码
<div #scrollMe style="height: 100px; overflow: scroll"> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> </div> <button (click)="goToScrollBottom()">发送</button>
2、组件代码
import {Component} from '@angular/core'; // 滚动条使用组件 import {ElementRef,AfterViewChecked,ViewChild} from "@angular/core"; @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent implements AfterViewChecked { constructor() { } @ViewChild("scrollMe") // 获取元素 public myScrollContainer: ElementRef; // 其实上面两句代码可以写成: // @ViewChild("scrollMe") myScrollContainer; ngAfterViewChecked() { this.scrollToBottom(); } // 方法调用 goToScrollBottom() { this.scrollToBottom(); } scrollToBottom() { this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; } }原文链接:https://www.f2er.com/angularjs/146626.html