【问题标题】:Delete button element from array loop Angular从数组循环Angular中删除按钮元素
【发布时间】:2020-05-22 15:58:40
【问题描述】:

我正在尝试从第一个和第二个索引循环的数组中删除/移除按钮,并仅在最后一个索引值或循环处显示。

下面是方法代码:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular';
  userForm = new FormGroup({
    name: new FormControl(),
    age: new FormControl()
  });

  masterData = [{
      name: 'alex',
      age: 20,
      button: 'no'
    },
    {
      name: 'bony',
      age: 21,
      button: 'no'
    },
    {
      name: 'acute',
      age: 23,
      button: 'yes'
    }
  ]
  ngOnInit() {

  }
html:

<div *ngFor="let data of masterData">
  <form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
    Name: <input formControlName="name" placeholder="Enter Name"> Age: <input formControlName="age" placeholder="Enter Age">
    <button type="submit">Submit</button>
    <button type="button">display at last </button>

  </form>
</div>

上面是集成对象数组的代码,其中“最后显示”按钮应该只显示数组的最后一个对象。

接下来的方法是从 dom 获取按钮的元素引用,但它不起作用。请帮我解决这个问题

为了更好地理解这里是一个代码链接: https://stackblitz.com/edit/angular-chdfdh?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

  • 您可以使用 Array.filter 创建一个新数组,其中只有 button = yes 的元素
  • 类似这样的东西:masterData.filter(ob => ob.button !== 'no')
  • 是的,添加可变按钮的目的是为了更好地理解,在名为按钮的对象中不会有任何值:否/是...我已添加以显示位置
  • 你可以添加一个变量到你的*ngFor 来检测循环的最后一项
  • 我用例子为你添加了答案

标签: javascript html angular7


【解决方案1】:

你可以从*ngFor获取索引,像这样:

<div *ngFor="let data of masterData; let last = last">
  <form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
    Name: <input formControlName="name" placeholder="Enter Name"> Age: <input formControlName="age" placeholder="Enter Age">
    <button type="submit">Submit</button>
    <button type="button" *ngIf="last">display at last </button>
  </form>
</div>

所以发生的事情是我在 for 循环的最后一项中添加了一个名为 last 的变量。然后仅在变量为真时才显示按钮,即最后一项。

编辑

我看到masterData 中还有一个变量。您可以使用其中的变量来显示按钮。

例如:

<div *ngFor="let data of masterData; let last = last">
  ...
    <button type="button" *ngIf="data.button === 'yes'">display at last </button>
  </form>
</div>

【讨论】:

  • 您的第一种方法对我来说效果很好,因为在我的对象中我没有名为按钮的变量,我只是在此处添加以更好地理解
  • 可以请帮我在 app.ts 中而不是在 html 中实现
猜你喜欢
  • 2013-05-29
  • 2012-02-15
  • 2014-09-08
  • 2012-11-26
  • 2012-01-20
  • 2013-05-04
  • 2020-03-27
  • 2010-12-29
相关资源
最近更新 更多