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

后端 未结 11 2599
时光取名叫无心
时光取名叫无心 2020-11-29 18:10

When trying ViewChild I am getting the error. Error is \"An argument for \'opts\' was not provided.\"

Both @ViewChild is giving the error.



        
相关标签:
11条回答
  • 2020-11-29 18:20

    Angular 8

    In Angular 8, ViewChild has another param

    @ViewChild('nameInput', {static: false}) component : Component
    

    You can read more about it here and here

    Angular 9 & Angular 10

    In Angular 9 default value is static: false, so doesn't need to provide param unless you want to use {static: true}

    0 讨论(0)
  • 2020-11-29 18:21

    In Angular 8 , ViewChild takes 2 parameters:

    Try like this:

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

    Explanation:

    { static: false }

    If you set static false, the child component ALWAYS gets initialized after the view initialization in time for the ngAfterViewInit/ngAfterContentInit callback functions.

    { static: true}

    If you set static true, the child component initialization will take place at the view initialization at ngOnInit

    By default you can use { static: false }. If you are creating a dynamic view and want to use the template reference variable, then you should use { static: true}

    For more info, you can read this article

    Working Demo

    In the demo, we will scroll to a div using template reference variable.

     @ViewChild("scrollDiv", { static: true }) scrollTo: ElementRef;
    

    With { static: true }, we can use this.scrollTo.nativeElement in ngOnInit, but with { static: false }, this.scrollTo will be undefined in ngOnInit , so we can access in only in ngAfterViewInit

    0 讨论(0)
  • 2020-11-29 18:21

    you should use second argument with ViewChild like this:

    @ViewChild("eleDiv", { static: false }) someElement: ElementRef;
    
    0 讨论(0)
  • 2020-11-29 18:24

    In Angular 8 , ViewChild takes 2 parameters

     @ViewChild(ChildDirective, {static: false}) Component
    
    0 讨论(0)
  • 2020-11-29 18:24

    it is because view child require two argument try like this

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

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

    0 讨论(0)
  • 2020-11-29 18:26

    Regex for replacing all via IDEA (tested with Webstorm)

    Find: \@ViewChild\('(.*)'\)

    Replace: \@ViewChild\('$1', \{static: true\}\)

    0 讨论(0)
提交回复
热议问题