错误TS2554:需要2个参数,但@ViewChild却有1个

Akh*_*mar 28 typescript viewchild angular angular7 angular8

我正在使用ViewChild,如下所示:

@ViewChild("InternalMedia") localStream;
@ViewChild("emoji") mEmoji;
Run Code Online (Sandbox Code Playgroud)

一直工作到angular-7.x

我将其升级到angular-8.x后,就开始出现以下错误

.../call_emoji/component.ts(41,4): error TS2554: Expected 2 arguments, but got 1.
Run Code Online (Sandbox Code Playgroud)

我检查了https://angular.io/api/core/ViewChild,并将其更改为

@ViewChild("InternalMedia",{static:false}) remoteStream;
Run Code Online (Sandbox Code Playgroud)

有用。我没有得到什么静态效果,像以前一样工作应该有什么价值?

Ste*_*anu 45

迁移到Angular 8后,您应该手动声明其是否静态

@ViewChild(QuilldEditorComponent, {static: true}) quillEditorComponentInstance;
Run Code Online (Sandbox Code Playgroud)

如果您还有其他问题要询问或需要更多详细信息,请阅读此问题 https://github.com/angular/angular-cli/issues/14553 或查看官方文档 https://angular.io/guide/static -查询迁移

// query results available in ngOnInit
@ViewChild('foo', {static: true}) foo: ElementRef; 

OR

// query results available in ngAfterViewInit
@ViewChild('foo', {static: false}) foo: ElementRef;

Run Code Online (Sandbox Code Playgroud)


Mat*_*hyn 14

根据Angular文档的静态检查

在更改检测运行之前是否解析查询结果(即仅返回静态结果)。如果未提供此选项,则编译器将退回到其默认行为,即使用查询结果来确定查询解析的时间。如果任何查询结果在嵌套视图中(例如* ngIf),则将在运行更改检测后解决查询。否则,将在运行更改检测之前解决该问题。

有效地,这确定了何时运行查询以检索元素。如果设置为false,则查询将在检测到任何更改后运行。如果设置为true,它将立即运行。

有关详细信息以及为什么包含此选项,请参阅此Github问题

您可能正在寻找的行为是设置static为false。这将导致旧的行为。但是,如果组件的视图不是动态的(例如,您不使用* ngIf),则应该可以安全地将其设置为true。

  • 他们不是说Angular 2之后一切都会向后兼容吗? (4认同)