我的表格如下。您能告诉我如何在用户更改contingency
和budget1
属性的值时动态填充计算字段值(budget2
)吗?我已经尝试了很多方法但没有运气:(
html的
<form [formGroup]="form" (submit)="createOrUpdate(form)" novalidate>
<ion-item>
<ion-input type="text" formControlName="budget1" [(ngModel)]="project.budget1"></ion-input>
</ion-item>
<ion-item>
<ion-input type="number" formControlName="budget2" [(ngModel)]="project.budget2"></ion-input>
</ion-item>
<ion-item>
<ion-input type="text" formControlName="contingency" [(ngModel)]="project.contingency" disabled></ion-input>
</ion-item>
</form>
model.ts
export class ProjectDetail {
budget1: number;
budget2: number;
contingency: number;
}
.TS
export class ProjectComponent {
@Input() data: any;
@Output() onSelectProject: EventEmitter<any> = new EventEmitter<any>();
form: FormGroup; project: ProjectDetail = new ProjectDetail();
constructor(private formBuilder: FormBuilder) {
this.initForm();
}
//init Form
initForm() {
this.form = this.formBuilder.group({
budget1: ['', Validators.required],
budget2: ['', Validators.required],
contingency: [{ value: 0, disabled: true }],
});
}
}
答案 0 :(得分:1)
您可以使用 ngModelChange
并将值传递给函数,然后在函数内计算它们,
<ion-item>
<ion-input type="text" (ngModelChange)="calculateContingency()" formControlName="budget1" [(ngModel)]="project.budget1"></ion-input>
</ion-item>
<ion-item>
<ion-input type="number" (ngModelChange)="calculateContingency()" formControlName="budget2" [(ngModel)]="project.budget2"></ion-input>
</ion-item>
<ion-item>
并在 TS
calculateContingency(){
this.contingency = this.project.budget2 + this.project.budget1;
}