首页 文章

Angular - 如何使用ngFor?

提问于
浏览
0

我想重构我的代码 . 我在我的 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>

我想循环每个Model以显示firstName和lastName

我有这个错误:

未捕获错误:模板解析错误:无法绑定到'firstName',因为它不是'app-portrait'的已知属性 .

我做错了什么?

1 回答

  • 1

    ngFor 没什么问题 . 恭喜!

    但是,您的 Component 's properties are specified incorrectly. If you want to inject them with values from your HTML, you' ll需要通过 @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>
    

相关问题