gpt4 book ai didi

javascript - Angular 让条件元素自动滚动到 View 中的最佳方法

转载 作者:行者123 更新时间:2023-12-01 00:19:55 24 4
gpt4 key购买 nike

我有一个使用 *ngIf 条件有条件插入的元素。当它插入时,我想将其滚动到 View 中。以下技术可行,但看起来很笨拙,我想改进它。

          <app-text-create id="textcreate" *ngIf="modeNewEntry"          
(load)="document.getElementById('textcreate').scrollIntoView()"
></app-text-create>

当组件状态属性 modeNewEntry 变为 true 时,文本输入框将插入到页面底部。如果没有 scrollIntoView() 调用,它通常不可见。

是否有比 document.getElementById(..) 表达式更好的方法来访问 HTMLElement

PS。我正在使用的 IDE WebStorm 认为 document 引用未定义,尽管这确实有效。这是一个错误还是有原因?

最佳答案

在包装 div 中添加组件:

<div #textCreate>
<app-text-create id="textcreate" *ngIf="modeNewEntry">
</app-text-create>
</div>

然后,当您单击按钮将 modeNewEntry 设置为 true 时,还要对 ElementRef 调用 scrollIntoView()div 的 nativeElement:

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

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
modeNewEntry = false;
@ViewChild('textCreate', { static: false }) textCreateComponent: ElementRef;

showComponent() {
this.modeNewEntry = true;
this.textCreateComponent.nativeElement.scrollIntoView();
}
}
<小时/>

Here's a Working Code Demo 🚀 for your ref.

关于javascript - Angular 让条件元素自动滚动到 View 中的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59508486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com