从数组循环中删除按钮元素 Angular

问题描述 投票:1回答:1

我试图从第1和第2个索引循环的数组中删除按钮,只在最后一个索引值或循环中显示。

下面是方法的代码。

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>

以上是整合了对象数组的代码,其中 "display at last "按钮应该只显示在数组的最后一个对象上。

遵循的方法是从dom中获取按钮的元素ref,但它不工作。请帮我解决这个问题

为了更好的理解,这里有一个代码的链接。https:/stackblitz.comeditangular-chdfdh?file=src%2Fapp%2Fapp.component.ts。

javascript html angular7
1个回答
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>

所以现在的情况是,我添加了一个叫做 last 到for循环的最后一项。 然后只有在变量为真时才显示按钮,即最后一项。

编辑

我看到,在这个变量中也有一个 masterData. 你可以直接使用其中的变量来显示按钮。

比如说,你可以使用该变量来显示按钮。

<div *ngFor="let data of masterData; let last = last">
  ...
    <button type="button" *ngIf="data.button === 'yes'">display at last </button>
  </form>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.