Angular-ngFor如何工作? [英] Angular - How ngFor works?
问题描述
我想重新输入我的代码.
我的section-portrait.component.html
I want to refacto my code.
I have this ngFor in my 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>
我想在每个模型上循环显示名字和姓氏
I want to loop on every Model to display there firstName and lastName
我有这个错误:
未捕获的错误:模板解析错误:由于无法绑定到名字" 不是'app-portrait'的已知属性.
Uncaught Error: Template parse errors: Can't bind to 'firstName' since it isn't a known property of 'app-portrait'.
我做错了什么?
推荐答案
您的ngFor
没有问题.恭喜!
但是,您Component
的属性指定不正确.如果要使用HTML中的值注入它们,则需要通过@Input
公开它们.
However, your Component
's properties are specified incorrectly. If you want to inject them with values from your HTML, you'll need to expose them through @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>
这篇关于Angular-ngFor如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!