viewchild angular code example

Example 1: angular viewchild input element value

// in html
<input #input type="text">
// in .ts
@ViewChild('input') input:ElementRef; 
//Output value
console.log(this.input.nativeElement.value);

Example 2: view child in angular

content_copy
      
      import {Component, Directive, Input, ViewChild} from '@angular/core';

@Directive({selector: 'pane'})
export class Pane {
  @Input() id!: string;
}

@Component({
  selector: 'example-app',
  template: `
    <pane id="1" *ngIf="shouldShow"></pane>
    <pane id="2" *ngIf="!shouldShow"></pane>

    <button (click)="toggle()">Toggle</button>

    <div>Selected: {{selectedPane}}</div>
  `,
})
export class ViewChildComp {
  @ViewChild(Pane)
  set pane(v: Pane) {
    setTimeout(() => {
      this.selectedPane = v.id;
    }, 0);
  }
  selectedPane: string = '';
  shouldShow = true;
  toggle() {
    this.shouldShow = !this.shouldShow;
  }
}

Example 3: viewchild for ngfor

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

-------------------------

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>; // or ElementRef if only need to grab element

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}