簡體   English   中英

如何使用@ViewChild 獲取 HTML 元素 Angular

[英]How to get HTML element Angular using @ViewChild

有 HTML 的組件:

<div class="filter" #filterContainer>   

在另一個組件中,我監聽 body 滾動並嘗試將 scrollTop 應用於元素#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)
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM