简体   繁体   中英

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

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;

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM