【问题标题】:*ngFor is undefined in custom template and defined / works in ul > li*ngFor 在自定义模板中未定义,在 ul > li 中定义/工作
【发布时间】:2023-03-08 18:25:01
【问题描述】:

我相信这不是重复的,因为我花了几个小时后没有找到类似的案例。

我刚开始学习 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>

我错过了什么吗?谢谢

【问题讨论】:

  • 您永远不会将任何输入传递给您的 app-companion-item 组件。从那以后它又能从哪里得到同伴呢? angular.io/guide/…
  • 您的companion-item.component 中缺少@Input 属性

标签: angular ngfor


【解决方案1】:

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

&lt;app-companion-item *ngFor="let companion of companions" [companion]="companion"&gt;&lt;/app-companion-item&gt;

并在您的 app-companion-item 类中使用 @Input('companion') companion: any;(如果可能的话,请创建一个接口)。

查看这些文档Angular Component interaction

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 2015-01-20
    相关资源
    最近更新 更多