英文:
Angular ngFor IntelliSense Shows 'any' Instead of the Type in visual studio code
问题
当在Angular模板中使用ngFor
循环遍历一个Person数组时,变量person
的类型显示为any
而不是其实际类型。如何确保在循环内部对person
进行正确的类型识别?
代码:
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>
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论