Angular @ViewChild() error: Expected 2 arguments, but got 1

Introduction

This is the error I have got when I upgraded from Angular 5 to Angular 8 latest version. 

What is ViewChild?

ViewChild is a decorator in Angular written as @ViewChild. It gives the user access to child components, directives, and DOM elements from the parent component class. It returns the very first child of the specific reference. 
  • The view of the child component will be rendered after the ngAfterViewInit hook of the component life cycle. So we have to implement the ngAfterViewInit in our component.
The error is shown as ViewChild is expecting two arguments instead of one. We used to write ViewChild as follows. The first argument pass to ViewChild is the type of the component, directive, template reference we want to access. 

   @ViewChild('scrollLeft') scrollLeft: ElementRef;

Now in Angular latest version, we have to pass the second argument as well which is as follows:

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

What static will do?
static - We can pass true to resolve query results before change detection runs. The static parameter for @ViewChild() and @ContentChild() determines when the query results become available.
If we set static to false it means the component will get initialized after the view has been created.
With {static: true} the query resolves once the view has been created, but before change detection runs. The result of the query will never be updated to reflect changes to your view such as changes to ngIf and ngFor blocks. With this option, we can use scrollLeft in the ngOnInit() itself. We can create dynamic views using this option as well as view in ngOnInit(). 
With dynamic queries (static: false), the query resolves after either ngAfterViewInit() or ngAfterContentInit() for @ViewChild. The result will be updated for changes to your view, such as changes to ngIf and ngFor blocks.

Comments