Friday, October 2, 2020

Angular viewchild, viewchildren, contentchild, contentchildren example.

 @viewchild and @viewchildren both are component interactive decorators which are serving the mechanism of accessing the element, component, directives. Both are working similarly only the difference is @viewchild querying one element.@viewchildren querying multiple elements.

import { Component, OnInit, ViewChild,ViewChildren,QueryList } from '@angular/core';
 
@ViewChild(TeacherComponent,{ static: false }) teacher: TeacherComponent;
 @ViewChild('div',{ static: false }) element: ElementRef;
  @ViewChild('username',{ static: false }) userelement: ElementRef;
@ViewChildren(TeacherComponent) vcteacher: QueryList<TeacherComponent>;
 
ngAfterViewInit() {
    console.log(this.teacher.scienceteacher);
    console.log(this.userelement);
    this.element.nativeElement.style.display='none';
    console.log(this.vcteacher)
 
  }
 
  •  Add viewchild,viewchildren,QueryList in the import declaration from '@angular/core'
  • @ViewChild(TeacherComponent,{ static: false }) teacher: TeacherComponent  -  Defined as viewchild selector type component and static false.
  • From angular 8 onwards one parameter extra added for static true or false.What is static parameter will see later.
  • @ViewChild('div',{ static: false }) element: ElementRef  -  Defined as viewchild selector type ElementRef and static false.
  • @ViewChildren(TeacherComponent) vcteacher: QueryList<TeacherComponent>  -  Same as viewchild but returns querylist.
  • Viewchild and viewchildren component, element, directives are available after ngAfterViewInit event.

Find below the full code and execution result.

school.component.ts - this is parent component

import { Component, OnInit, ViewChild, ElementRef,  ViewChildren, QueryList} from '@angular/core';
import { TeacherComponent } from '../teacher/teacher.component';
 
@Component({
  selector: 'app-school',
  templateUrl: './school.component.html',
  styleUrls: ['./school.component.css']
})
export class SchoolComponent implements OnInit {
  @ViewChild(TeacherComponent,{ static: false }) teacher: TeacherComponent;
  @ViewChildren(TeacherComponent) vcteacher: QueryList<TeacherComponent>;
  schscienceteacher:string;
  @ViewChild('div',{ static: false }) element: ElementRef;
  @ViewChild('username',{ static: false }) userelement: ElementRef;
  constructor() { }
 
  ngOnInit() {
 
  }
  ngAfterViewInit() {
    console.log(this.teacher.scienceteacher);
    console.log(this.userelement);
    this.element.nativeElement.style.display='none';
    console.log(this.vcteacher)
  }
}
 
 

school.component.html - this is parent component

<p>school works!</p>
<p>{{schscienceteacher}}</p>
<input type="text" #username name="username">
<div #div>hello</div>
<app-teacher name="teacher"></app-teacher>

teacher.component.ts - this is child component

import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-teacher',
  templateUrl: './teacher.component.html',
  styleUrls: ['./teacher.component.css']
})
export class TeacherComponent implements OnInit {
scienceteacher:string="William";
mathteacher:string="John";
physicsteacher:string="johnson";
  constructor() { }
 
  ngOnInit() {
  }
 
}
 

teacher.component.html - this is child component

<p>teacher works!</p>

angular viewchild,viewchildren example

  • console.log(this.teacher.scienceteacher)  -  William is displayed in the developer console because of "teacher" defined as viewchild component of teacher.component. scienceteacher is variable of teacher.component.ts(child component).
  • console.log(this.userelement)  -  Input ElementRef object is displayed.
  • this.element.nativeElement.style.display='none'  -  Hiding the div element through viewchild elementref.
  • console.log(this.vcteacher)  -  Finally displaying the child component querylist using viewchildren.

What is ChangeDetectorRef in Angular?

Once you get the variable value from viewchild you can not change the value in ngAfterviewinit event. You will get the below error.

angular-ExpressionChangedAfterItHasBeenCheckedError

We can resolve this error using changedetectorref.Refer below code.

import { Component, OnInit, ViewChild, ElementRef, ViewChildren, QueryList, ChangeDetectorRef } from '@angular/core';
 
 constructor(private changedetect: ChangeDetectorRef) { }
ngAfterViewInit() {
    this.schscienceteacher=this.teacher.scienceteacher="kennady";
     this.changedetect.detectChanges();
  }
 

How to hide and show the child component element from the parent component using viewchild?

school.component.ts - this is parent component

import { Component, OnInit, ViewChild } from '@angular/core';
import { TeacherComponent } from '../teacher/teacher.component';
 
@Component({
  selector: 'app-school',
  templateUrl: './school.component.html',
  styleUrls: ['./school.component.css']
})
export class SchoolComponent implements OnInit {
  @ViewChild(TeacherComponent,{ static: false }) teacher: TeacherComponent;
 
  constructor() { }
 
  ngOnInit() {
 
  }
  ngAfterViewInit() {
    this.teacher.elementteacherdiv.nativeElement.style.display='none';
  }
}

teacher.component.ts - this is child component

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
 
@Component({
  selector: 'app-teacher',
  templateUrl: './teacher.component.html',
  styleUrls: ['./teacher.component.css']
})
export class TeacherComponent implements OnInit {
@ViewChild('divteacher',{ static: false }) elementteacherdiv: ElementRef;
  constructor() { }
 
  ngOnInit() {
  }
 
}

teacher.component.html - this is child component

<div #divteacher>Teacher div</div>

Have you seen the above code? We will start from child component for better understanding. In the child component getting the #divteacher element using viewchild.Then parent component getting elementteacherdiv using viewchild component and at last hiding the element in ngAfterviewinit function. 

What is contentchild and contentchildren in angular?

"@contentchild" and "@contentchildren" same as "@viewchild" and "@viewchildren" but it will work only in ng-content."@contentchild" targetting single element, component, directives."@contentchildren" getting the querylist within ng-content.

Before starting contentchild we suggest you go through our previous tutorial angular ng content example for better understanding.

schoolmaster.component.ts - this is parent component

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-schoolmaster',
  templateUrl: './schoolmaster.component.html',
  styleUrls: ['./schoolmaster.component.css']
})
export class SchoolmasterComponent implements OnInit {
 
  constructor() { }
 
  ngOnInit() {
 
  }
}
 

schoolmaster.component.html - this is parent component

<p>schoolmaster works!</p>
 
<div>
    <app-teachermaster>
        <h1 #hellodiv>hello</h1>
        <h1 #hellodivquery>this is test1</h1>
        <h1 #hellodivquery>this is test2</h1>
        <p>paragraph hellos</p>
    </app-teachermaster>
</div>

teachermaster.component.html - this is child component

<p>teachermaster works!</p>
 
 <div>   
 <ng-content select="h1"></ng-content>
 </div>

teachermaster.component.ts - this is child component

import { Component, OnInit, ContentChild, ElementRef, QueryList, ContentChildren } from '@angular/core';
 
@Component({
  selector: 'app-teachermaster',
  templateUrl: './teachermaster.component.html',
  styleUrls: ['./teachermaster.component.css']
})
export class TeachermasterComponent implements OnInit {
  @ContentChildren ('hellodivquery') cteacher: QueryList<ElementRef>;
  @ContentChild('hellodiv',{ static: false }) contenthellodiv: ElementRef;
 
  constructor() { }
 
  ngOnInit() {
  }
  ngAfterContentInit() {
 
    console.log(this.contenthellodiv.nativeElement.innerHTML);
    let querydata: ElementRef[] = this.cteacher.toArray();
    console.log(querydata);
}
 
}
 

angular contentchild, contentchildren example

 

ng-content selecting all h1 element from parent component then displaying the element in developer console using contentchild and contentchildren.

No comments:

Post a Comment

Lab 09: Publish and subscribe to Event Grid events

  Microsoft Azure user interface Given the dynamic nature of Microsoft cloud tools, you might experience Azure UI changes that occur after t...