Angular 8 DOM Queries: ViewChild and ViewChildren Example

The @ViewChild and @ViewChildren decorators in Angular provide a way to access and manipulate DOM elements, directives and components…

In this tutorial, we’ll see an Angular 8 example of how to use the two decorators.

You can use ViewChild if you need to query one element from the DOM and ViewChildren for multiple elements.

We’ll be using an online development IDE available from https://stackblitz.com/ so you don’t need to set up your local development machine for Angular at this point.

Head over to Stackblitz, sign in with your GitHub account and choose an Angular workspace:

You should be presented with an online IDE with an Angular 8 project:

Our Angular project contains the usual App component and a child component called HelloComponentand defined in the src/app/hello.component.ts file with the followign code:

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

@Component({
  selector: 'hello',
  template: `# Hello !
`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
}

The component accepts a name property and uses an inline template which simply displays the value passed via the name property from the parent component.

In the component decorator, we used hello as the selector for the component so in the the HTML template of the App component defined in the src/app/app.component.html file, we include the child component using the following code:



  Start editing to see some magic happen :)


After running our Angular application the hello component is rendered and becomes part of the DOM so we can query it just like any normal DOM element.

What’s ViewChild in Angular?

ViewChild is a decorator that creates a view or DOM query. According to the docs

Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.
The decorator takes the following meta information:

  • selector - the selector of the element to query. This can be a directive type or a name.
  • read - read a different token from the queried elements.
  • static - This is new in Angular 8 and indicates whether or not to resolve query results before change detection runs.

ViewChild can take the following selectors:

  • Classes with the @Component or @Directive decorators i.e components and directives,
  • Template reference variables,
  • Providers,
  • TemplateRef

Now, let’s go back to our src/app/app.component.ts file and let’s see how we can query the child component using ViewChild. First, change the code accordingly:

import { Component, ViewChild, AfterViewInit } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';
  @ViewChild(HelloComponent, {static: false}) hello: HelloComponent;

  ngAfterViewInit() {
    console.log('Hello ', this.hello.name); 
  }
}

In the console, you should get Hello Angular:

Now, let’s explain the code.

First, we imported HelloComponent and ViewChild and AfterViewInit from the @angular/corepackage:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { HelloComponent } from './hello.component';

Next, we create a query called hello that takes HelloComponent as the selector and has static equals to false:

@ViewChild(HelloComponent, {static: false}) hello: HelloComponent;

In Angular 8, timing for ContentChild and ViewChild needs to be specified explicitly.

See: ​Why do I have to specify [{static: false}](https://angular.io/guide/static-query-migration#why-do-i-have-to-specify-static-false-isnt-that-the-default "{static: false}")? Isn’t that the default?

Next, in the ngAfterViewInit() life-cycle hook, we can use the query to access the DOM element for the hello component. In our example, we accessed the name property of the component, after it’s mounted in the DOM, which contains the Angular string:

ngAfterViewInit() {
    console.log('Hello ', this.hello.name); 
}

We can access any properties and even methods from the queried component.

Note*: View queries are set before the *ngAfterViewInit* callback is called.*## Querying Standard HTML Elements with Template References

We can also query standard HTML elements using ViewChild and template reference variables. Let’s go back to our src/app/app.component.html file and change it as follows:




  Start editing to see some magic happen :)


We simply added the helloRef template reference to our hello component. Now let’s change our code to access the component using its reference. Go back to the src/app/app.component.ts file and change accordingly:

import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';
  @ViewChild(HelloComponent, {static: false}) hello: HelloComponent;

  @ViewChild('pRef', {static: false}) pRef: ElementRef;

    ngAfterViewInit() {
    console.log(this.pRef.nativeElement.innerHTML); 
    this.pRef.nativeElement.innerHTML = "DOM updated successfully!!!"; 
  }
}

We import ElementRef and we create a query configuration to access the `````` DOM element with the #pRef template reference as follows:

@ViewChild('pRef', {static: false}) pRef: ElementRef;

Next, in the ngAfterViewInit() method we can access and modify the native DOM element using the nativeElement object of ElementRef:

 @ViewChild('pRef', {static: false}) pRef: ElementRef;

    ngAfterViewInit() {
    console.log(this.pRef.nativeElement.innerHTML);
    this.pRef.nativeElement.innerHTML = "DOM updated successfully!!!"; 
  }

This is the live example from this link.

What’s ViewChildren in Angular?

ViewChildren is another property decorator which is used to query the DOM for multiple elements and return a QueryList.

According to the docs:

You can use ViewChildren to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.
Let’s see an example.

Go to the src/app/app.component.html file and update it as follows:





We are simply diplsaying the hello component three times. Let’s now query the DOM. Open the src/app/app.component.ts file and change it as follows:

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

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';
  @ViewChildren(HelloComponent) hellos: QueryList;

  ngAfterViewInit() {

     this.hellos.forEach(hello => console.log(hello));

  }
}

You should this output in the console:

Now, let’s explain the code.

First we import ViewChildren, AfterViewInit and QueryList from @angular/core package.

Next, we create a vquery configuration for accessing multiple DOM elements:

@ViewChildren(HelloComponent) hellos: QueryList;

@ViewChildren returns a QueryList which stores a list of items. When the state changes Angular will automatically update this query list.

Finally, in the ngAfterViewInit() method, we can iterate over the query list and log each DOM element:

  ngAfterViewInit() {
     this.hellos.forEach(hello => console.log(hello));
  }

You can find the live example from this link.

Conclusions

In this tutorial, we’ve seen how we can access and modify the DOM in Angular 8 using ViewChild and ViewChildren decorators and a couple of other APIs like QueryList and ngAfterViewInit()

#angular #web-development

What is GEEK

Buddha Community

Angular 8 DOM Queries: ViewChild and ViewChildren Example
Clara  Gutmann

Clara Gutmann

1598716260

Angular 8 CRUD Example | Angular 8 Tutorial For Beginners

Angular 8 CRUD is a basic operation to learn Angular from scratch. We will learn how to build a small web application that inserts, read data, update and delete data from the database. You will learn how to create a MEAN Stack web application. In this Angular 8 Tutorial Example, you will learn a new framework by building a crud application.

New features of Angular 8

You check out the new features in brief on my  Angular 8 New Features post.

I have designed this Angular 8 CRUD Tutorial, especially for newcomers, and it will help you to up and running with the latest version of Angular, which is right now 8.

#angular #angular 8 #angular 8 crud

I am Developer

1610191977

Angular 11 Google Social Login Example

Angular 9/10/11 social login with google using angularx-social-login library example. In this tutorial, i will show you step by step on how to implement google social login in angular 11 app.

And also, this tutorial will show you How to login into Angular 10/11 application with google using angularx-social-login library in angular 11 app.

Google Login Integration In Angular 11 App

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Google Login App

https://www.tutsmake.com/angular-11-google-social-login-example/

#angular 11 google login #angular 11 social-login example #login with google button angular 8/9/10/11 #angular 10/11 login with google #angular 10 social google login #angular social login google

I am Developer

1609902140

Angular 11 Facebook Social Login Example

Angular 9/10/11 social login with facebook using angularx-social-login library example. In this tutorial, i would love to show you how to integrate facebook social login in angular 11 app.

And you will learn how to add facebook social login button with angular reactive login form.

Angular 11 Social Login with Facebook Tutorial

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Facebook Login App

https://www.tutsmake.com/angular-11-facebook-login-tutorial-example/

#angular 11 facebook login #angular 11 social-login example #login with facebook button angular 8/9/10/11 #angular 10/11 login with facebook #angular 10 social facebook login #angular social login facebook

I am Developer

1610191977

Angular 11 Google Social Login Example Tutorial

Angular 9/10/11 social login with google using angularx-social-login library example. In this tutorial, i will show you step by step on how to implement google social login in angular 11 app.

And also, this tutorial will show you How to login into Angular 10/11 application with google using angularx-social-login library in angular 11 app.

Google Login Integration In Angular 11 App

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Google Login App

https://www.tutsmake.com/angular-11-google-social-login-example/

#angular 11 google login #angular 11 social-login example #login with google button angular 8/9/10/11 #angular 10/11 login with google #angular 10 social google login #angular social login google

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli