首页 > 解决方案 > 如何使用@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

标签: angularangular8

解决方案


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)
  }
}

推荐阅读