如何修复 Angular 9 @ViewChild Expected 2 arguments, but got 1: An argument for 'opts' was not provided.

问题:

你正在尝试编译你的 Angular 9.x 应用程序,但你看到类似这样的错误消息

viewchild_error.txt
app/my-component/my-component.component.ts:24:4 - error TS2554: Expected 2 arguments, but got 1.

24   @ViewChild(MyOtherComponent) myOtherComponent: MyOtherComponent;
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  ../node_modules/@angular/core/core.d.ts:7888:47
    7888     (selector: Type<any> | Function | string, opts: {
                                                       ~~~~~~~
    7889         read?: any;
         ~~~~~~~~~~~~~~~~~~~
    7890         static: boolean;
         ~~~~~~~~~~~~~~~~~~~~~~~~
    7891     }): any;
         ~~~~~
    An argument for 'opts' was not provided.

解决方案

在错误消息指定的位置找到代码中的此行:

viewchild_wrong.ts
@ViewChild(MyOtherComponent) myOtherComponent: MyOtherComponent;

并添加

viewchild_opts.ts
{static: false}

作为 @ViewChild() 声明的第二个参数:

viewchild_fixed.ts
@ViewChild(MyOtherComponent, {static: false}) myOtherComponent: MyOtherComponent;

在大多数情况下,你想使用 static: false。有关何时使用 static: true 而不是 static: false 的详细信息,请参见StackOverflow 上的此帖子


Check out similar posts by category: Angular, Javascript, Typescript