【问题标题】:Angular arrays and ngFor角度数组和 ngFor
【发布时间】:2020-09-28 09:30:00
【问题描述】:

我有一个带有列表的 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>

和带有数组的组件 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 下等...

【问题讨论】:

  • 会有多少表格?如果很少有表单在点击时使用 ng-hide/show 或 ng-if 并使用 ngFor 的索引来引用 abc 数组索引。
  • 会有很多表格,我发布我的任务的简化版本。
  • 好的,myArr 数组,是不是只能引用到 abc?
  • 是的,它就在那里
  • 好的,我有一个适合你的例子,希望能指引你正确的方向。

标签: javascript html arrays angular typescript


【解决方案1】:

在 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

【讨论】:

    【解决方案2】:

    我想您是在问如何将一个数组中的相应值放在列表中的一项下方,例如在 1 旁边按 add 会显示 a,按 3 会显示 c。

    我认为您最好的选择是将循环的索引传递给您的函数“表达式”。您可以通过将 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 循环和索引显示它们。

    希望对你有所帮助?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2021-04-28
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多