angular - Angular - ngFor 如何工作?
问题描述
我想重构我的代码。我有这个 ngFor 在我的section-portrait.component.html
<app-portrait *ngFor="let model of models"
[firstName]="model.firstName"
[lastName]="model.lastName"
></app-portrait>
这是我的 portrait.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-portrait',
templateUrl: './portrait.component.html',
styleUrls: ['./portrait.component.scss']
})
export class PortraitComponent implements OnInit {
firstName: string;
lastName: string;
constructor() {
}
ngOnInit() {
}
}
和我的portrait.component.html
<h4>
<a href="#">{{ firstName }} {{ lastName }}</a>
</h4>
我想在每个模型上循环显示 firstName 和 lastName
我有这个错误:
未捕获的错误:模板解析错误:无法绑定到“firstName”,因为它不是“app-portrait”的已知属性。
我做错了什么?
解决方案
你的没有什么问题ngFor
。恭喜!
但是,您Component
的属性指定不正确。如果你想用 HTML 中的值注入它们,你需要通过@Input
.
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-portrait',
templateUrl: './portrait.component.html',
styleUrls: ['./portrait.component.scss']
})
export class PortraitComponent implements OnInit {
@Input() firstName: string;
@Input() lastName: string;
constructor() {
}
ngOnInit() {
}
}
如果您愿意,您可能有兴趣更进一步:
@Input() model: Model;
<app-portrait *ngFor="let model of models" [model]="model"></app-portrait>
推荐阅读
- c# - 多处理中程序集引用的共享内存
- python - 定义并设为全局变量后未在子程序中定义变量
- bigdata - 大数据结构
- git - Git如何签出提交进行一些更改并将其推送回相同的提交
- postgresql - PostgreSQL 空连接
- python - 包含 pybindIETFXMLEncoder 类的用户何时可以使用下一个 pyangbind 版本
- pine-script - PineScript - 为变量设置颜色输入
- minio - 分布式 MINIO 部署在池中复制服务器
- obfuscation - ConfuserEx 不加密
- stream - Cupy 流同步使用 with 语句