Search code examples
angularviewchild

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;

Solution

  • 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.