首页 > 解决方案 > 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”的已知属性。

我做错了什么?

标签: angularngfor

解决方案


你的没有什么问题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>

推荐阅读