【问题标题】:Using @ViewChild in Angular `strict`mode在 Angular `strict` 模式下使用 @ViewChild
【发布时间】:2021-06-29 14:54:27
【问题描述】:

在Angular严格模式下使用@ViewChild的常用方法是什么?

例如,当我按照documentation 中所述对材料表进行排序时

@ViewChild(MatSort) sort: MatSort;

编译器说:

错误 TS2564:属性“排序”没有初始值设定项,并且未在构造函数中明确分配。

作为一种可能的解决方案,我可以使用

@ViewChild(MatSort, { static: false }) sort!: MatSort;

...但在我看来,这更像是一种解决方法。

【问题讨论】:

  • 您可能只是将其设为可选(即sort?: MatSort),这至少可以让您在使用它之前检查它是否确实存在(从而避免错误)。我不觉得使用?! 真的有什么问题,但是使用? 会强制你在使用前打开它,这很有帮助。
  • @ChrisGilardi 建议比使用非空断言运算符 (!) 更好。 ViewChild 本质上是对您的视图的查询,因此您不能始终保证它不会未定义(或者您的视图的未来更改不会使其未定义)。
  • 不幸的是 ? 它可能是未定义的,而不仅仅是 null,因此我无法将它分配给我的 datasource.sort。

标签: angular angular-material


【解决方案1】:

删除{ static: false } 部分似乎是正确的。所以sort 的有效声明是:

@ViewChild(MatSort) sort!: MatSort;

【讨论】:

  • {static:true} 的使用仅适用于“ViewChild”,它们在应用中始终可见
猜你喜欢
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 2015-08-05
  • 2020-06-13
  • 2015-12-08
  • 1970-01-01
相关资源
最近更新 更多