* ngFor在自定义模板中未定义,并且已在ul> li中定义/工作

时间:2018-08-06 06:47:15

标签: angular ngfor

我相信这不是重复的,因为我花了几个小时才发现类似的情况。

我刚刚开始学习Angular。

我不明白为什么* ngFor在自定义模板中未定义并且在ul> li中已定义/工作。

下面的代码产生以下结果:

companions-list works!

I am in companion-item.component.html
companion is null
I am in companion-item.component.html
companion is null
I am in companion-item.component.html
companion is null

Companion from UL - LI - name: Alex; rating: 8.4

Companion from UL - LI - name: Ben; rating: 8.2

Companion from UL - LI - name: Charlie; rating: 8.6

companions-list.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-companions-list',
  templateUrl: './companions-list.component.html',
  styleUrls: ['./companions-list.component.css']
})
export class CompanionsListComponent implements OnInit {

  companions = [
    {name: 'Alex', rating: 8.4},
    {name: 'Ben', rating: 8.2},
    {name: 'Charlie', rating: 8.6}
  ];

  constructor() { }    
  ngOnInit() {
  }
}

companions-list.component.html

<div>
  companions-list works!

  <div *ngIf="companions">
    <app-companion-item *ngFor="let companion of companions"></app-companion-item>
  </div>
  <ul>
    <li *ngFor="let companion of companions">
        <div class="boxed">
        Companion from UL - LI - name: {{ companion.name }}; rating: {{ companion.rating }}
        </div>
        <br/>
    </li>
  </ul>
</div>

companion-item.component.html:

<div class="boxed">
  I am in    companion-item.component.html
  <div *ngIf="companion == null">companion is null</div>
  <div *ngIf="companion">
    companion: name: {{ companion.name }}; rating: {{ companion.rating }}
  </div>
</div>

我错过了什么吗?谢谢

1 个答案:

答案 0 :(得分:0)

您缺少组件([companion]="companion")的输入

<app-companion-item *ngFor="let companion of companions" [companion]="companion"></app-companion-item>

并在您的app-companion-item类中使用@Input('companion') companion: any;(如果将其更改为另一种类型,请尽可能创建一个接口)。

请参阅这些文档Angular Component interaction