[英]Angular - How ngFor works?
I want to refacto my code. 我想重新验证我的代码。 I have this ngFor in my section-portrait.component.html
我的section-portrait.component.html
有这个ngFor
<app-portrait *ngFor="let model of models"
[firstName]="model.firstName"
[lastName]="model.lastName"
></app-portrait>
Here is my portrait.component.ts
这是我的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() {
}
}
And my portrait.component.html
还有我的portrait.component.html
<h4>
<a href="#">{{ firstName }} {{ lastName }}</a>
</h4>
I want to loop on every Model to display there firstName and lastName 我想在每个模型上循环显示那里的名字和姓氏
And I have this error: 我有这个错误:
Uncaught Error: Template parse errors: Can't bind to 'firstName' since it isn't a known property of 'app-portrait'. 未捕获的错误:模板解析错误:无法绑定到“名字”,因为它不是“应用程序肖像”的已知属性。
What did I do wrong? 我做错了什么?
There's nothing wrong with your ngFor
. 您的ngFor
没有任何问题。 Congratulations! 恭喜!
However, your Component
's properties are specified incorrectly. 但是,您的Component
的属性指定不正确。 If you want to inject them with values from your HTML, you'll need to expose them through @Input
. 如果要使用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() {
}
}
If you wanted, you might be interested in going one step further: 如果您愿意,您可能有兴趣进一步进行以下操作:
@Input() model: Model;
<app-portrait *ngFor="let model of models" [model]="model"></app-portrait>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.