Angular在尝试使用反应式表单动态创建表单字段时自动发出post请求
我试图创建一个角度反应式表单,用户可以通过按Add(+)按钮在一个表单中输入多个日期,该按钮将动态创建表单字段以获取日期类型输入。我希望用户能够添加任意多的日期,添加所有日期后,用户将按下提交按钮,数据将发送到后端。但在我的代码中,每当我按下Add(+)按钮创建一个新表单字段时,它都会自动从sample.component.ts文件调用onSubmit()函数,而不仅仅是调用addReportingDate()函数,该函数发出了一个不需要的post请求。如何解决此问题 sample.component.htmlAngular在尝试使用反应式表单动态创建表单字段时自动发出post请求,angular,typescript,angular-reactive-forms,Angular,Typescript,Angular Reactive Forms,我试图创建一个角度反应式表单,用户可以通过按Add(+)按钮在一个表单中输入多个日期,该按钮将动态创建表单字段以获取日期类型输入。我希望用户能够添加任意多的日期,添加所有日期后,用户将按下提交按钮,数据将发送到后端。但在我的代码中,每当我按下Add(+)按钮创建一个新表单字段时,它都会自动从sample.component.ts文件调用onSubmit()函数,而不仅仅是调用addReportingDate()函数,该函数发出了一个不需要的post请求。如何解决此问题 sample.compon
<h2 mat-dialog-title>
KPI
</h2>
<div mat-dialog-content class="create-department-form">
<form
[formGroup]="kpiForm"
class="department-form"
(ngSubmit)="onSubmit()"
>
<mat-form-field>
<mat-label>KPI Name</mat-label>
<label>
<input formControlName="name" matInput/>
</label>
</mat-form-field>
<mat-form-field>
<mat-label>KPI Weight</mat-label>
<label>
<input type="number" formControlName="weight" matInput/>
</label>
</mat-form-field>
<mat-form-field>
<mat-label>Select Department Name</mat-label>
<input type="text"
placeholder="Pick one"
aria-label=""
matInput
formControlName="departmentId"
[matAutocomplete]="auto1"
(keyup)="onKey($event)">
<mat-autocomplete #auto1="matAutocomplete">
<mat-option *ngFor="let department of departments" [value]="department.id">
{{department.id + ' - ' + department.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field>
<mat-label>Select Employee List</mat-label>
<input type="text"
placeholder="Pick one"
aria-label=""
matInput
formControlName="employeeId"
[matAutocomplete]="auto2"
(keyup)="onKey($event)">
<mat-autocomplete #auto2="matAutocomplete">
<mat-option *ngFor="let employee of employees" [value]="employee.id">
{{employee.id + ' - ' + employee.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field>
<mat-label>Select Goal KPI Name</mat-label>
<input type="text"
placeholder="Pick one"
aria-label=""
matInput
formControlName="goalKpiId"
[matAutocomplete]="auto"
(keyup)="onKey($event)">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let goalKpi of goalKpis" (click)="updateGoalKpiSpaceStatus(goalKpi)" [value]="goalKpi.id">
{{goalKpi.id + ' - ' +goalKpi.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<span *ngIf="selectedGoalKpiWeight">
<span class="status">Selected Goal KPI Weight: {{selectedGoalKpiWeight ? selectedGoalKpiWeight : 'N/A'}}</span>
<span class="status">Total Weight Taken: {{selectedGoalKpiTakenWeight ? selectedGoalKpiTakenWeight : 'N/A'}}</span>
<span class="status">Remaining Weight: {{selectedGoalKpiRemainingWeight ? selectedGoalKpiRemainingWeight : 'N/A'}}</span>
</span>
<mat-form-field>
<mat-label>Add Reporting Date(s)</mat-label>
<div formArrayName="reportingDates">
<div *ngFor="let date of reportingDates.controls; let dateIndex=index" [formGroupName]="dateIndex">
<input type="date" formControlName="date" matInput/>
<button id="deleteButton" (click)="deleteReportingDate(dateIndex);" mat-mini-fab color="warn" aria-label="Delete reporting date.">
<mat-icon>delete</mat-icon>
</button>
</div>
<button id="addButton" (click)="addReportingDate()" mat-mini-fab color="primary" aria-label="Add another reporting date.">
<mat-icon>add</mat-icon>
</button>
</div>
</mat-form-field>
</form>
</div>
<div mat-dialog-actions>
<button
(click)="onSubmit()"
type="submit"
mat-raised-button
color="primary"
[disabled]="!kpiForm.valid"
>
Submit
</button>
<button mat-raised-button color="warn" type="button" (click)="onNoClick()">
Cancel
</button>
</div>
关键绩效指标
KPI名称
KPI权重
选择部门名称
{{department.id+'-'+department.name}
选择员工列表
{{employee.id+'-'+employee.name}
选择目标KPI名称
{{goalKpi.id+'-'+goalKpi.name}
所选目标KPI权重:{{selectedGoalKpiWeight?selectedGoalKpiWeight:'N/A'}
总重量:{{selectedGoalKpiTakenWeight?selectedGoalKpiTakenWeight:'N/A'}
剩余重量:{{selectedGoalKpiRemainingWeight?selectedGoalKpiRemainingWeight:'N/A'}
添加报告日期
删除
添加
提交
取消
sample.component.ts文件
@Component({
selector: 'app-add-edit-kpi-dialog',
templateUrl: './add-edit-kpi-dialog.component.html',
styleUrls: ['./add-edit-kpi-dialog.component.scss']
})
export class AddEditKpiDialogComponent implements OnInit {
kpiForm: FormGroup;
goalKpis: IGoalKpi[];
departments: IDepartmentList[];
employees: IEmployeeList[];
value: string;
selectedGoalKpiWeight: number;
selectedGoalKpiTakenWeight = 0;
selectedGoalKpiRemainingWeight = 0;
constructor(
private dialogRef: MatDialogRef<AddEditKpiDialogComponent>,
private formBuilder: FormBuilder,
private dialog: MatDialog,
private goalKpiService: GoalKpiService,
private kpiService: KpiService,
private departmentService: DepartmentService,
private employeeService: EmployeeService,
private loaderService: NgxUiLoaderService,
private alertService: AlertService,
@Inject(MAT_DIALOG_DATA) public data: {
isEdit: boolean,
kpiData: IKpi
}
) {
this.kpiForm = this.formBuilder.group({
name: ['', Validators.required],
weight: ['', Validators.required],
goalKpiId: ['', Validators.required],
departmentId: ['', Validators.required],
employeeId: ['', Validators.required],
reportingDates: this.formBuilder.array([this.formBuilder.group({date: ''})]),
});
}
ngOnInit(): void {
this.loadAllRequiredData();
if (this.data.isEdit) {
this.populateForm();
}
}
get reportingDates() {
return this.kpiForm.get('reportingDates') as FormArray;
}
addReportingDate() {
this.reportingDates.push(this.formBuilder.group({date: ''}));
}
deleteReportingDate(index) {
this.reportingDates.removeAt(index);
}
populateForm() {
this.kpiForm.controls.name.setValue(this.data.kpiData.name);
this.kpiForm.controls.weight.setValue(this.data.kpiData.weight);
this.kpiForm.controls.goalKpiId.setValue(this.data.kpiData.goalKpiName);
this.kpiForm.controls.employeeId.setValue(this.data.kpiData.employeeName);
this.kpiForm.controls.departmentId.setValue(this.data.kpiData.departmentName);
}
loadAllRequiredData() {
this.loaderService.start();
forkJoin([
this.departmentService.getDepartmentByName(''),
this.employeeService.getEmployeeByName(''),
this.goalKpiService.getGoalKpiByName(''),
]).subscribe(response => {
this.departments = response[0].data;
this.employees = response[1].data;
this.goalKpis = response[2].data;
}, error => {
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
}
updateGoalKpiSpaceStatus(goalKpi: any) {
this.loaderService.start();
this.selectedGoalKpiWeight = goalKpi.weight;
this.kpiService.getToalWeightOfKpisByGoalKpiId(goalKpi.id).subscribe(response => {
this.selectedGoalKpiTakenWeight = response.data;
}, error => {
this.loaderService.stop();
}, () => {
this.selectedGoalKpiRemainingWeight = this.selectedGoalKpiWeight - this.selectedGoalKpiTakenWeight;
this.loaderService.stop();
});
}
loadDataOnSearchResult(name: string, fieldName: string){
if (fieldName === 'goalKpiId') {
this.loaderService.start();
this.goalKpiService.getGoalKpiByName(name)
.subscribe(response => {
this.goalKpis = response.data;
}, error => {
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
} else if (fieldName === 'departmentId') {
this.loaderService.start();
this.departmentService.getDepartmentByName(name)
.subscribe(response => {
this.departments = response.data;
}, error => {
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
} else if (fieldName === 'employeeId') {
this.loaderService.start();
this.employeeService.getEmployeeByName(name)
.subscribe(response => {
this.employees = response.data;
}, error => {
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
}
}
onKey(event: any) {
console.log(event.target);
console.log(event.target.attributes.formControlName.value);
this.value = event.target.value;
this.loadDataOnSearchResult(this.value, event.target.attributes.formControlName.value);
}
onSubmit() {
this.loaderService.start();
const {id, name, weight, goalKpiId, goalKpiName, departmentId, employeeId} = this.kpiForm.value;
const kpiData = {
name,
weight: +weight,
goalKpiName
};
if (this.data.isEdit) {
this.kpiService.updateKpiIdByGoalIdKpiId(this.data.kpiData.goalKpiId, this.data.kpiData.id, kpiData)
.subscribe(response => {
this.alertService.success('Kpi updated successfully');
this.dialogRef.close();
}, error => {
this.alertService.danger(error.error.message);
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
} else {
this.kpiService.addNewEmployeeIdByKpiIdEmployeeId(goalKpiId, employeeId, kpiData)
.subscribe(response => {
this.alertService.success('Kpi created successfully');
this.dialogRef.close();
}, error => {
this.alertService.danger(error.error.message);
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
}
}
onNoClick() {
this.dialogRef.close({cancel: true});
}
}
@组件({
选择器:“应用程序添加编辑kpi对话框”,
templateUrl:'./添加编辑kpi对话框.component.html',
样式URL:['./添加编辑kpi对话框.component.scss']
})
导出类AddEditKpiDialogComponent实现OnInit{
kfiform:FormGroup;
守门员:IGoalKpi[];
部门:IDepartmentList[];;
员工:IEEmployeeList[];
值:字符串;
selectedGoalKpiWeight:数字;
selectedGoalKpiTakenWeight=0;
selectedGoalKpiRemainingWeight=0;
建造师(
私有dialogRef:MatDialogRef,
私有formBuilder:formBuilder,
私人对话:MatDialog,
私人守门员服务:守门员服务,
私人kpiService:kpiService,
私人部门服务:部门服务,
私人雇员服务:雇员服务,
专用装载机服务:NgxUiLoaderService,
私人警报服务:警报服务,
@注入(MAT_对话框_数据)公共数据:{
isEdit:boolean,
kpiData:IKpi
}
) {
this.kfiform=this.formBuilder.group({
名称:['',验证器。必需],
重量:['',验证器。必需],
goalKpiId:['',验证器。必需],
部门ID:['',验证器。必需],
employeeId:['',验证器。必需],
reportingDates:this.formBuilder.array([this.formBuilder.group({date:'}]),
});
}
ngOnInit():void{
此.loadAllRequiredData();
if(this.data.isEdit){
this.populateForm();
}
}
获取报告日期(){
将此.kfiform.get('reportingDates')作为FormArray返回;
}
addReportingDate(){
this.reportingDates.push(this.formBuilder.group({date:'}));
}
删除报告日期(索引){
这个.reportingDates.removeAt(索引);
}
populateForm(){
this.kfiform.controls.name.setValue(this.data.kpiData.name);
this.kfiform.controls.weight.setValue(this.data.kpiData.weight);
this.kfiform.controls.goalKpiId.setValue(this.data.kpiData.goalKpiName);
this.kfiform.controls.employeeId.setValue(this.data.kpiData.employeeName);
this.kfiform.controls.departmentId.setValue(this.data.kpiData.departmentName);
}
loadAllRequiredData(){
this.loaderService.start();
分叉连接([
此.departmentService.getDepartmentByName(“”),
此.employeeService.getEmployeeByName(“”),
这个.goalKpiService.getGoalKpiByName(“”),
]).订阅(响应=>{
this.departments=响应[0]。数据;
this.employees=response[1]。数据;
this.goalKpis=响应[2]。数据;
},错误=>{
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
}
updateGoalKpiSpaceStatus(goalKpi:any){
this.loaderService.start();
this.selectedGoalKpiWeight=goalKpi.weight;
this.kpiService.getToAllweightokPisbyGoalkPiId(goalKpi.id).subscribe(response=>{
this.selectedGoalKpiTakenWeight=response.data;
},错误=>{
this.loaderService.stop();
}, () => {
this.selectedGoalKpiRemainingWeight=this.selectedGoalKpiWeight-this.selectedGoalKpiTakenWeight;
this.loaderService.stop();
});
}
loadDataOnSearchResult(名称:字符串,字段名:字符串){
如果(fieldName==='goalKpiId'){
this.loaderService.start();
this.goalKpiService.getGoalKpiByName(名称)
.订阅(响应=>{
this.goalKpis=response.data;
},错误=>{
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
}else if(fieldName==='departmentId'){
this.loaderService.start();
this.departmentService.getDepartmentByName(名称)
.订阅(响应=>{
this.departments=response.data;
},错误=>{
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
}else if(fieldName=='employeeId'){
this.loaderService.start();
this.employeeService.getEmployeeByName(名称)
.订阅(响应=>{
this.employees=response.data;
},错误=>{
this.loaderService.stop();
}, () => {
this.loaderService.stop();
});
}
}
onKey(事件:任意){
console.log(event.target);
console.log(event.target.attributes)。
<button id="addButton" type="button"