Angular:在(更改)事件上添加动态生成的输入字段数据的问题 [英] Angular: Issue in adding dynamically generated input field data on the (change) event
问题描述
我具有一项功能,需要在单击按钮时发送动态生成的输入字段.
I have a feature where I need to send dynamically generated input fields on button click.
为了更好的理解,我在 stackblitz 上重新创建了问题.
I have recreated the problem on stackblitz for better understanding.
在该应用中,当我输入resourceQuantity时,resourceId字段是动态生成的. 我的问题是单独识别这些字段,然后单击一下按钮即可将其发送到服务器端.
In that app, when I enter resourceQuantity, the resourceId fields are dynamically generated. My issue is to identify those fields individually and send them on server side on single button click.
我在stackblitz上发现的这种解决方案是类似的,但在我的问题是,我不是删除或添加按钮单击,而是(更改)事件.
This solution I've found on stackblitz is similar, but in my problem I am not removing or adding on button clicks, but (change) event instead.
这是 HTML 代码:
<mat-form-field>
<input matInput type="number" formControlName="resourceQuantity" [(ngModel)]="resourceQuantity" placeholder="Enter Resource Quantity" (change)="somethingChanged()"/>
</mat-form-field><br/><br/>
<div>
<ul>
<li *ngFor="let item of counter(resourceQuantity)">
<input matInput type="number" placeholder="Enter Resource Number" formControlName="resourceId"/>
</li>
</ul>
</div>
这是 TS 代码:
ngOnInit() {
this.form = new FormGroup({
'employeeId': new FormControl(null, {validators: [Validators.required]}),
'employeeName': new FormControl(null, {validators: [Validators.required]}),
'resourceQuantity': new FormControl(null, {validators: [Validators.required]}),
'resourceId': new FormControl(null, {validators: [Validators.required]})
});
}
somethingChanged() {
console.log(this.resourceQuantity);
}
counter(i: number) {
return new Array(i);
}
请让我知道解决我的问题的最佳方法.谢谢.
Kindly let me know the best solution to my problem. Thanks.
推荐答案
避免同时使用ngModel
和formControl
.您可以在组件中使用formArray
以及getter函数来获得结果.
Avoid using ngModel
and formControl
together. You can make use of formArray
along with getter functions in your component to get your result.
编辑:我已编辑代码以反映您所请求的更改,方法是订阅resourceQuantity
formControl
上的valueChanges
,并在检测到更改时生成formArray
.这样可以实时创建资源.
Edit: I have edited my code to reflect the change you requested by subscribing to valueChanges
on the resourceQuantity
formControl
and generating the formArray
when it detects the change. This creates the resources in real time.
Edit: Do not forget to unsubscribe from valueChanges
to prevent memory leakage. I have updated my Stackblitz to show the same.
这是 StackBlitz
这篇关于Angular:在(更改)事件上添加动态生成的输入字段数据的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!