簡體   English   中英

如何使用 ngfor 循環顯示數組中的每個組件

[英]How to display each component in an array with an ngfor loop

我正在設置一個頁面來保存來自用戶的一堆數據輸入,一個組件user-info包含一個由 n 個其他組件組成的數組,稱為semester-info

我有一個ngfor循環遍歷一組組Components並嘗試顯示所有組件。 相反,它只顯示文本Object object 我有組件工作,如果我改為

<app-empty-term id = "1" semsester={{semesterCount}} startYear={{currentUserYear}} term ={{currentUserTerm}} class="card">

它按預期顯示,所以我知道該組件按預期工作。

我已經確保將元素添加到我的術語數組中,這是正確的,如果我做類似的事情

{{element.name}}

我得到了數組中每個組件的預期答案。

我已經做了很多研究並且沒有太多的運氣,這讓我開始懷疑這是否可能,或者我是否應該以不同的方式來解決這個問題

<div id="sampleContainer" class="card-container" *ngFor="let element of terms">
        <div>{{element}}</div>
    <!-- <app-empty-term  id = "1" semsester={{semesterCount}} startYear= {{currentUserYear}} term ={{currentUserTerm}} class="card"></app- empty-term> -->
    </div>

這段代碼的注釋部分是我所期望的一些示例,在這種情況下,如果未注釋,則將有 n 個 app-empty-term 組件用於大小為 n 的術語數組,但是它們沒有鏈接到我的術語數組所以如果我嘗試訪問他們的數據,預期的數據將不存在

我希望該組件顯示 n 次,但它只顯示文本 Object object n 次。

如果您在每次迭代中的elementcomponent ,那么這應該可以按預期工作,您可以在此處了解有關*ngComponentOutlet的更多信息ngComponentOutlet

<div id="sampleContainer" class="card-container" *ngFor="let element of terms">
    <ng-container *ngComponentOutlet="element"></ng-container>
</div>

理想情況下,您的EmptyTermComponent上有一個@Input屬性。 像這樣的東西:

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

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

  @Input() term: any;

  constructor() { }

  ngOnInit() {
  }

}

然后您將term作為輸入傳遞給您的父組件:

像這樣的東西:

<div id="sampleContainer" class="card-container" *ngFor="let term of terms">
    <!-- <div>{{element}}</div> -->
    <app-empty-term
    [term]=term
    class="card">
  </app-empty-term>
</div>

假設您有如下所示的terms數組:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  terms = [
    { id: 1, semesterCount: 1, startYear: 2021, term: 1, name: 'Term 1' },
    { id: 2, semesterCount: 2, startYear: 2022, term: 2, name: 'Term 2' },
    { id: 3, semesterCount: 3, startYear: 2023, term: 3, name: 'Term 3' },
    { id: 4, semesterCount: 4, startYear: 2024, term: 4, name: 'Term 4' },
  ];
}

這是您參考的工作示例 StackBlitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM