'this' - 元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引类型

问题描述 投票:0回答:1

我定义了 3 个 @Viewchild 模板引用和一个数组

  @ViewChild('one') one!: TemplateRef<any>;
  @ViewChild('two') two!: TemplateRef<any>;
  @ViewChild('three') three!: TemplateRef<any>;

  templatesList = ['one','two'];
  
  templateRefsList: Array<TemplateRef<any>> = [];

现在 AfterViewInit,我想推送与数组中的元素匹配的 templatesRef

  for (let i = 0; i < templatesList.length, i++) {
    this.templateRefsList.push(this[templatesList[i]])
  }

但是在访问'this'时,出现以下错误。

元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引类型

如何将 templateRef 元素推送到循环列表中?

angular
1个回答
0
投票

templatesList
没有显式类型,被推断为
string[]
。但是为了通过索引访问 vlass 的属性,它需要具有类型
keyof YourComponent
。因此,您需要指定数组的类型,如下所示:

export class YourComponent {
  @ViewChild('one') one!: TemplateRef<any>;
  @ViewChild('two') two!: TemplateRef<any>;
  @ViewChild('three') three!: TemplateRef<any>;

  templatesList: (keyof YourComponent)[] = ['one','two'];
  
  templateRefsList: Array<TemplateRef<any>> = [];

  yourFunction() {
    for (let i = 0; i < templatesList.length, i++) {
      this.templateRefsList.push(this[templatesList[i]])
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.