Angular - ngFor 是如何工作的?

Angular - How ngFor works?

我想重构我的代码。 我的 section-portrait.component.html

中有这个 ngFor
<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

我有这个错误:

Uncaught Error: Template parse errors: Can't bind to 'firstName' since it isn't a known property of '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>