簡體   English   中英

Angular arrays 和 ngFor

[英]Angular arrays and ngFor

我有一個帶有列表的 html 組件

<div *ngFor="let item of myArr">
  <ul>
    <li>
      {{ item }}
      <span>
        <mat-icon (click)="expression($event)">add</mat-icon>
      </span>
      <ng-container
        ><h2 *ngFor="let item of textArr">
          {{ item }}
        </h2></ng-container
      >
    </li>
  </ul>
</div>

和帶有 arrays 的組件 ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
})
export class ChildComponent implements OnInit {
  myArr = ['1', '2', '3', '4'];

  abc = ['a', 'b', 'c', 'd'];

  textArr = [];

  constructor() {}

  ngOnInit(): void {}
  expression(ev: Event) {
    console.log(ev);

    this.textArr.push(this.abc);
  }
}

我該怎么做,當我點擊 + 1 前面的內容時,'a' form abc 將僅顯示在 1 下,如果我點擊 + 前面的內容 2,那么 abc 中的 b 應該顯示在 2 下, ETC...

我需要的

我想您是在問如何將一個數組中的相應值放在列表中的某個項目下方,例如按 1 旁邊的添加將顯示 a,按 3 將顯示 c。

我認為你最好的選擇是將循環的索引傳遞給你的 function '表達式'。 您可以通過將index as i添加到循環中來獲取循環的索引,因此它看起來像這樣。

<div *ngFor="let item of myArr; index as i">
  <ul>
    <li>
      {{ item }}
      <span>
        <mat-icon (click)="expression($event, i)">add</mat-icon>
      </span>
      ...

現在您需要一個結構來存儲已添加的值,我會考慮使用 2D 數組(數組數組)來存儲您添加的值並使用您的 for 循環和索引顯示它們。

希望這可以幫助

在 for 循環中使用索引。

我有一個例子

<h2>Form list</h2>
<div *ngFor="let form of formList; let i = index">
  <ul>
    <li>
      <h4>{{ form.formLable }}</h4> 
       <div>
         <button (click)="loadForm(i)">View {{ form.formLable }}</button>
      </div>
      <div *ngIf="form.isLoaded">
         Do what ever strategy to load a form in
         If many many many forms look at loading components in dynamically
      </div>
    </li>
  </ul>
</div>

這是一個工作示例。

https://stackblitz.com/edit/angular-8clu3r?file=src%2Fapp%2Fform-list%2Fform-list.component.html

暫無
暫無

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

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