Home > Enterprise >  What is the difference between component selector and query selector in Angular ViewChild
What is the difference between component selector and query selector in Angular ViewChild

Time:07-21

According to Angular ViewChild Documentation, ViewChild Selector can the Component Class or a query string. Same result can be achieved with both. So what is the difference between these two, when to use what and performance wise which is better to use?

app.component.html

<hello #hello></hello>


app.component.ts

@ViewChild('hello') hello: HelloComponent;

and

app.component.html

<hello></hello>


app.component.ts

@ViewChild(HelloComponent) hello: HelloComponent;

CodePudding user response:

The main difference is that instead of using component name, you can use normal html tag as follows:

<section #hello></section>

,and it's nothing to do about the performance since in both format an extra tag is added to the DOM, and must be rendered by the browser engine.

It's just matter of being a readable code or not.

CodePudding user response:

Angular Component isn't an HTML Element, it's an instance on a class component you created.

What doesn't that mean? it means that you sometimes need to call a method or use a property of component you use, this isn't applicable using querySelector since Angular Component isn't an HTML Element.

The solution provided by Angular is @ViewChild selector.

Check this example:

https://angular-ivy-ap7bsj.stackblitz.io

CodePudding user response:

1 - Multiple selection


<app-hello #hello1></hello>
<app-hello #hello2></hello>

In that case, to select a single component, the string is required, or you have to use @ViewChildren

2 - Directive selection


<app-hello #hello routerLink="hello" routerLinkActive="active"></hello>

In this code, you have 3 elements: the component, the routerLink directive and the routerLinkActive directive. Using the string representation can let you select the type easily.

@ViewChild('hello', { read: RouterLinkActiveDirective }) helloRouter;

In short, the only difference is versatility and code readability.

  • Related