英文:
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
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论