Angular ngFor IntelliSense在Visual Studio Code中显示’any’而不是类型。

huangapple go评论92阅读模式
英文:

Angular ngFor IntelliSense Shows 'any' Instead of the Type in visual studio code

问题

当在我的Angular模板中使用ngFor来遍历一个Person数组时,变量person的类型显示为any而不是它的实际类型。如何确保在循环内正确识别person的类型?

英文:

Question:

When using ngFor in my Angular template to loop through a Person array, the type of the variable person is displayed as any instead of its actual type. How can I ensure proper type recognition for person within the loop

Angular ngFor IntelliSense在Visual Studio Code中显示’any’而不是类型。

Angular ngFor IntelliSense在Visual Studio Code中显示’any’而不是类型。

Code:

sample.component.ts

import { Component, OnInit } from '@angular/core';

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.scss']
})
export class SampleComponent implements OnInit {

  personArray: Person[];
  constructor() { }

  ngOnInit() {
    const person1 = new Person("Alice", 30);
    const person2 = new Person("Bob", 25);

    this.personArray = [person1, person2];
    
  }

}

sample.component.html

<div *ngFor="let person of personArray">
  {{person.name}}
</div>

答案1

得分: 1

希望这条消息能找到您。

要启用类型检查,您可以在您的tsconfig.json中添加strictTemplates选项,像这样:

"angularCompilerOptions": {
  "fullTemplateTypeCheck": true,
  "strictInjectionParameters": true,
  "strictTemplates": true
}

有关更多信息,请查看这里:https://angular.io/guide/template-typecheck

以及这里的配置:https://angular.io/guide/typescript-configuration

Angular ngFor IntelliSense在Visual Studio Code中显示’any’而不是类型。

Angular ngFor IntelliSense在Visual Studio Code中显示’any’而不是类型。

英文:

hope this message find you well.

To enable the type checking, you can add the strictTemplates option in your tsconfig.json like this:

  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true,
    "strictTemplates": true
  }

for more information please check here: https://angular.io/guide/template-typecheck

and the configurations here: https://angular.io/guide/typescript-configuration

Angular ngFor IntelliSense在Visual Studio Code中显示’any’而不是类型。

Angular ngFor IntelliSense在Visual Studio Code中显示’any’而不是类型。

huangapple
  • 本文由 发表于 2023年8月9日 08:37:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76863888-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定