Mat按钮在* ngFor中单击以让index = index不会发生反应/触发动作 [英] Mat-Button click inside a *ngFor with let index = index does not react/fire action
问题描述
我目前正在一个项目中,我有一个reactive form array
,该项目将使用*ngIf
显示在模板上.我认为这是正常的用例,没什么特别的.但是现在我像这样构建
I am currently working on a project where I have a reactive form array
which will be displayed on the template using an *ngIf
. I think that's the normal use case and nothing special. But now I build this like
<div *ngFor="let control of form.controls['someArray'].value; let index = index">
[...]
<button mat-flat-button color="warn">Delete</button>
</div>
<button mat-flat-button color="primary">Add</button>
Delete
按钮对我的点击没有反应,但是Add
按钮却没有反应.由于某些原因,当我删除let index = index
时,它又可以工作了,或者我将按钮放在了*ngFor
之外.
The Delete
button does not react to my clicks, but the Add
button does. For some reason when I remove the let index = index
it works again or if I put the button outside of this *ngFor
.
希望您能帮助我.非常感谢你.到目前为止找不到任何解决方案.
I hope you can help me. Thank you very much. Couldn't find any solution so far.
示例: https://stackblitz.com/edit/angular-form -array-example-hq5tud
import { Component } from '@angular/core';
import { FormControl, FormGroup, FormArray, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form">
<input type="checkbox" formControlName="published"> Published
<div *ngIf="form.controls.published.value">
<h2>Credentials</h2>
<button (click)="addCreds()">Add</button>
<div formArrayName="credentials" *ngFor="let creds of form.controls.credentials?.value; let i = index">
<ng-container [formGroupName]="i">
<input placeholder="Username" formControlName="username">
<input placeholder="Password" formControlName="password">
<button mat-flat-button (click)="buttonClick()"> Test inside </button>
</ng-container>
</div>
<button mat-flat-button (click)="buttonClick()"> Test outside </button>
</div>
</form>
`,
})
export class AppComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
published: true,
credentials: this.fb.array([]),
});
}
addCreds() {
const creds = this.form.controls.credentials as FormArray;
creds.push(this.fb.group({
username: '',
password: '',
}));
}
buttonClick() {
console.log('Clicked');
}
}
推荐答案
这是有效的示例,请检查链接
Here is the working example Please check the link
https://stackblitz.com/edit/angular-form -array-example-test123-2jzdij
这篇关于Mat按钮在* ngFor中单击以让index = index不会发生反应/触发动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!