4.1 ViewChild ViewChildren - quan1997ap/angular-app-note GitHub Wiki

Source: https://github.com/angular-vietnam/100-days-of-angular/blob/master/Day010-template-variable-viewchild-viewchildren.md

View child: Từ phần tử cha => truy cập tới 1 phần tử con

// View queries are set before the ngAfterViewInit callback is called.
ViewChild(selector: string | Function | Type<any>, opts?: {
  read?: any;
  static?: boolean;
})

Example 1:

<div #chartContainer></div>
export class AppComponent  {
  @ViewChild('chartContainer') container: ElementRef<HTMLDivElement>;
}
@ViewChild('nameForm', {
   read: ElementRef,
   static: true
}) form: ElementRef<HTMLFormElement>;

Chú thích

  • opts.read : Bạn cần lấy gì : directive, một component, một service, ..
  • static :
    • static = true : Nếu selector không nằm trong if/else tức là nó không thay đổi trong suốt thời gian sống của componen. Truy cập nó ở trong ngOnInit.
    • static = false : (giá trị mặc định) không thể dùng nó ở ngOnInit mà phải chạy ở ngAfterViewInit. Giá trị của child sẽ được gán khi change detection chạy.

View child: Từ phần tử cha => truy cập tới nhiều phần tử con dùng QueryList

Example 2:

<app-toggle></app-toggle>
<br>
<app-toggle></app-toggle>
@ViewChildren(ToggleComponent) toggleList: QueryList<ToggleComponent>;

ngAfterViewInit() {
  console.log(this.toggleList);
}

View child: Từ phần tử cha => truy cập tới nhiều phần tử con dùng QueryList

<app-toggle #toggle1 ></app-toggle>
<br>
<app-toggle #toggle2 ></app-toggle>
 @ViewChild("#toggle1") appToggleComponent1: AppToggleComponent;
 @ViewChild("#toggle2") appToggleComponent2: AppToggleComponent;
⚠️ **GitHub.com Fallback** ⚠️