top of page
Writer's pictureThe Tech Platform

The QueryList

The QueryList is the return type of ViewChildren and contentChildren . QueryList stores the items returned by the viewChildren or contentChildren in a list. The Angular updates this list, whenever the state of the application change. It does it on each change detection.


The QueryList also Implements an iterable interface. Which means you can iterate over it using for (var i of items) or use it with ngFor in template *ngFor="let i of items".


Changes can be observed by subscribing to the changes Observable.


You can use the following methods & properties.

  • first: returns the first item in the list.

  • last: get the last item in the list.

  • length: get the length of the items.

  • changes: Is an observable. It emits a new value, whenever the Angular adds, removes or moves the child elements.


ViewChildren Example

In the example below, we have three input elements all using the ngModel directive We use the ViewChildren to get the QueryList of all input elements


Finally, we can use the this.modelRefList.forEach to loop through the QueryList and access each element.

import { ViewChild, Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { NgModel } from '@angular/forms';
 
@Component({
  selector: 'app-viewchildren1',
  template: `
      <h1>ViewChildren Example</h1>
 
      <input name="firstName" [(ngModel)]="firstName">
      <input name="midlleName" [(ngModel)]="middleName">
      <input name="lastName" [(ngModel)]="lastName">
 
      <button (click)="show()">Show</button>
  
  `,
})
 
export class ViewChildrenExample1Component {
 
  firstName;
  middleName;
  lastName;
 
  @ViewChildren(NgModel) modelRefList: QueryList<NgModel>;
  
  show() {
 
    this.modelRefList.forEach(element => {
      console.log(element)
      //console.log(element.value)
    });
  }
}


Listening for QueryList Changes

We can subscribe to the changes observable to find if any new elements are added/removed or moved.

In the example below, we have included ngIf directive to hide/show the input elements.


We subscribe to the changes observable in the component class. Every time we use the ngIf to hide or add the component, the changes observable emits the latest QueryList.

 import { ViewChild, Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { NgModel } from '@angular/forms';
 
@Component({
  selector: 'app-viewchildren2',
  template: `
      <h1>ViewChildren Example</h1>
 
      <input *ngIf="showFirstName" name="firstName" [(ngModel)]="firstName">
      <input *ngIf="showMiddleName" name="midlleName" [(ngModel)]="middleName">
      <input *ngIf="showlastName" name="lastName" [(ngModel)]="lastName">
 
 
      <input type="checkbox" id="showFirstName" name="showFirstName" [(ngModel)]="showFirstName">
      <input type="checkbox" id="showMiddleName" name="showMiddleName" [(ngModel)]="showMiddleName">
      <input type="checkbox" id="showlastName" name="showlastName" [(ngModel)]="showlastName">
 
      <button (click)="show()">Show</button>
  
  `,
 
})
 
export class ViewChildrenExample2Component implements AfterViewInit {
 
  firstName;
  middleName;
  lastName;
 
  showFirstName=true;
  showMiddleName=true;
  showlastName=true;
 
  @ViewChildren(NgModel) modelRefList: QueryList<NgModel>;
 
  ngAfterViewInit() {
 
    this,this.modelRefList.changes
      .subscribe(data => {
        console.log(data)
      }
    )
  }
  
 
  show() {
    this.modelRefList.forEach(element => {
      console.log(element)
      //console.log(element.value)
    });
 
  }
}

Methods:


1. get()

Returns the QueryList entry at index.

get(index: number): T | undefined

Parameters indexnumber


Returns T | undefined


2. map()

map<U>(fn: (item: T, index: number, array: T[]) => U): U[]

Parameters fn(item: T, index: number, array: T[]) => U


Returns U[]


3. filter()

filter(fn: (item: T, index: number, array: T[]) => boolean): T[]

Parameters fn(item: T, index: number, array: T[]) => boolean


Returns T[]


4. find()

find(fn: (item: T, index: number, array: T[]) => boolean): T | undefined

Parameters fn - (item: T, index: number, array: T[]) => boolean


Returns T | undefined


5. reduce()

reduce<U>(fn: (prevValue: U, curValue: T, curIndex: number, array: T[]) => U, init: U): U

Parameters

fn - (prevValue: U, curValue: T, curIndex: number, array: T[]) => UinitU


Returns U


6. forEach()

forEach(fn: (item: T, index: number, array: T[]) => void): void

Parameters fn - (item: T, index: number, array: T[]) => void


Returns void


7. some()

some(fn: (value: T, index: number, array: T[]) => boolean): boolean

Parameters fn - (value: T, index: number, array: T[]) => boolean


Returns boolean


8. toArray()

Returns a copy of the internal results list as an Array.

toArray(): T[]Parameters

There are no parameters.

Returns T[]


9. toString()

toString(): stringParameters

There are no parameters.

Returns string


10. reset()

Updates the stored data of the query list, and resets the dirty flag to false, so that on change detection, it will not notify of changes to the queries, unless a new change occurs.

reset(resultsTree: (any[] | T)[], identityAccessor?: (value: T) => unknown): void

Parameters resultsTree - (any[] | T)[] - The query results to store


identityAccessor - (value: T) => unknownOptional function for extracting stable object identity from a value in the array. This function is executed for each element of the query result list while comparing current query list with the new one (provided as a first argument of the reset function) to detect if the lists are different. If the function is not provided, elements are compared as is (without any pre-processing). Optional. Default is undefined.


Returns void


11. notifyOnChanges()

Triggers a change event by emitting on the changes EventEmitter.

notifyOnChanges(): voidParameters

There are no parameters.

Returns void


12. setDirty()

internal

setDirty()Parameters

There are no parameters.


13. destroy()

internal

destroy(): voidParameters

There are no parameters.

Returns void





Resource: tektutorialshub.com, angular


The Tech Platform



0 comments

Commenti


bottom of page