Angular - How ngFor works?

大城市里の小女人 提交于 2019-12-13 06:31:18

问题


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>

Here is my 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

<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?


回答1:


There's nothing wrong with your ngFor. Congratulations!

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>


来源:https://stackoverflow.com/questions/53103390/angular-how-ngfor-works

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!