我有三个字段,例如“ Duration,Repeat,Complete Duration”。用户将以时间格式(HH:MM:SS)输入持续时间,并且他们将输入重复字段值,例如“ 5,10,4,9,7等”。根据两个字段的值,应填写完整的工期字段。
我尝试使用两个文本字段的NgModel角,然后将值乘以重复字段值。但是转换没有正确进行。
<div>
<input type="value" [(ngModel)]="user.hrDuration">
<input type="value" [(ngModel)]="user.minDuration">
<input type="value" [(ngModel)]="user.secDuration">
</div>
<div>
<input type="value" [(ngModel)]="user.repeat">
</div>
<div>
<input type="value" [(ngModel)]="user.hrDuration*user.repeat">
<input type="value" [(ngModel)]="user.minDuration*user.repeat">
<input type="value" [(ngModel)]="user.secDuration*user.repeat">
</div>
我已经尝试过了,但是问题是它直接乘以值,我需要转换,然后再乘以重复字段值。
预先感谢!
答案 0 :(得分:0)
您应该订阅输入的输入事件,以便知道它们何时更改:
<div>
<input type="value" [(ngModel)]="user.hrDuration" (input)="updateResult()">
<input type="value" [(ngModel)]="user.minDuration" (input)="updateResult()">
<input type="value" [(ngModel)]="user.secDuration" (input)="updateResult()">
</div>
<div>
<input type="value" [(ngModel)]="user.repeat" (input)="updateResult()">
</div>
<div>
<input type="text" [ngModel]="result.hrDuration">
<input type="text" [ngModel]="result.minDuration">
<input type="text" [ngModel]="result.secDuration">
</div>
,然后在Component中具有侦听方法:
export class AppComponent {
user = {
hrDuration: 1,
minDuration: 1,
secDuration: 1,
repeat: 1
}
result = {
hrDuration: this.user.hrDuration * this.user.repeat,
minDuration: this.user.minDuration * this.user.repeat,
secDuration: this.user.secDuration * this.user.repeat
}
updateResult() {
// do your conversion here
this.result.hrDuration = this.user.hrDuration * this.user.repeat;
this.result.minDuration = this.user.minDuration * this.user.repeat;
this.result.secDuration = this.user.secDuration * this.user.repeat;
}
}
这是一个有效的堆叠闪电战:https://stackblitz.com/edit/angular-2aukww
答案 1 :(得分:0)
我认为您应该使用onchange事件侦听器和返回结果的函数:
HTML:
<div>
<input type="value" [ngModel]="user.hours" (ngModelChange)="getResult()">
<input type="value" [ngModel]="user.minutes" (ngModelChange)="getResult()">
<input type="value" [ngModel]="user.seconds" (ngModelChange)="getResult()">
</div>
<div>
<input type="value" [ngModel]="user.repeat" (ngModelChange)="getResult()">
</div>
<div>
<input type="value" (ngModel)="user.result" readonly>
</div>
JS:
function getResult() {
if (isNaN($scope.user.hours) ||
isNaN($scope.user.minutes) ||
isNaN($scope.user.seconds) ||
isNaN($scope.user.repeat)) return $scope.user.result = "";
var total = ($scope.user.hours*60*60 + $scope.user.minutes*60 + $scope.user.seconds) * $scope.user.repeat;
var hh = Math.floor(total / (60*60));
if ( hh < 10 ) hh = '0' + hh;
var diff = total % (60*60);
var mm = Math.floor(diff / 60);
if ( mm < 10 ) mm = '0' + mm;
var ss = Math.floor(diff % 60);
if ( ss < 10 ) ss = '0' + ss;
$scope.user.result = hh + ':' + mm+ ':' + ss;
// of course you could also output something like
// 'X hours, Y minutes, Z seconds'
}
将结果显示为单个值将更清楚地显示最终值,因为将每个变量(小时,分钟和秒)乘以重复将不太直观。