【发布时间】: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