angular - 如何使用@ViewChild 获取 HTML 元素 Angular
问题描述
有带有 HTML 的组件:
<div class="filter" #filterContainer>
在另一个组件中,我听 body scroll 并尝试将 scrollTop 应用于 element #filterContainer
:
export class SkeletonComponent implements OnInit, AfterViewInit, OnChanges {
isSideBarOpen;
@ViewChild("filterContainer", {
read: ViewContainerRef,
static: false
})
el: ElementRef;
@HostListener("window:scroll", ["$event"])
public scroll($event): void {
let scrolled = $event.target.scrollingElement.scrollTop;
console.log(this.el);
}
}
但是当我得到的事件被触发时console.log(this.el);
是未定义的,为什么我无法访问元素#filterContainer
?
解决方案
viewChild 仅在您拥有模板引用变量的组件中可见。(并且必须阅读:ElementRef,而不是阅读:ViewContainerRef
如果您的组件有父组件,则需要从该父组件访问组件,然后访问 ViewChildren。是的,您可以使用父级的 ViewChild(或使用模板引用)访问子级
例如我们的孩子
@Component({
selector: 'hello',
template: `<h1 #filterContainer>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
@ViewChild('filterContainer',{static:false}) filterComponent
}
我们的父母
<hello #hello name="{{ name }}"></hello>
<button (click)="log(hello.filterComponent)">button</button>
<button (click)="log2()">button</button>
export class AppComponent {
name = 'Angular';
@ViewChild(HelloComponent,{static:false}) hello
//or
//@ViewChild('hello',{static:false,read:HelloComponent}) hello
log(element)
{
console.log(element.nativeElement.innerHTML)
}
log2()
{
console.log(this.hello.filterComponent)
}
}
推荐阅读
- node.js - mongodb updateOne 方法不适用于 mongoose 5.4.10
- angular - 如何根据剑道网格中的特定列条件更改行的颜色以获取角度
- python - pyautogui 自动降档/升档和 ctrl-c 不起作用
- php - localhost apache 服务器上的 Windows-1256 问题
- java - 具有其他 spring 数据源属性的外部化 DB url 配置
- ios - 在 UIAlert 之后执行 Segue
- python - 操作熊猫中另一个数据框中存在的数据框的行
- c# - 从子文件夹加载 xml 和 dll
- python - 如何从 Python 的官方文档中读取函数签名
- android - 在 transformClassesWithDexBuilder 处为 Android 客户端库编译新的 Places SDK 失败