我正在尝试创建一个显示时间格式的输入,但以分钟为单位保存一个值。例如:1:30的值为90。
我的第一个选择是使用指令。 现在,如果我将输入中的值更改为75,则显示的值应为1:15。 我不想使用@Output和EventEmitter并设置一种方法来更改我的值。
组件:
public value = 90;
查看:
<p><input [(appTimespan)]="value"></p>
<p>Value: {{ value }}</p>
指令(剪裁):
@Directive({ selector: '[appTimespan]'})
export class TimespanDirective {
@Input( 'appTimespan' ) value: string;
// @Output( 'out' ) update = new EventEmitter();
constructor(private element: ElementRef) {
// just to indicate the directive is applied
element.nativeElement.style.backroundColor = 'yellow';
}
@HostListener('change') onChange() {
// skip the code for calculations and formatting
this.value = 75;
this.element.nativeElement.value = '1:15';
// this.update.emit(75);
}
}
我输入的(display)值设置为'1:15',太好了... 但是视图中显示的值仍显示我的初始值90,我希望它是75。
答案 0 :(得分:1)
您可以使用管道显示分钟到小时的格式。
组件:
public value: number = 90;
查看:
<input type="number" [(ngModel)]="value" />
<p>Value: {{ value | toTime }}</p>
管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'toTime'})
export class ToTime implements PipeTransform {
convertMinsToHrsMins(minutes) {
let h:any = Math.floor(minutes / 60);
let m:any = minutes % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return h + ':' + m;
}
transform(value: number): string {
return this.convertMinsToHrsMins(value);
}
}
修改 您可以在组件中使用相同的管道获取小时数
submit(){
console.log(this.toTime.transform(this.value))
}
答案 1 :(得分:0)
我喜欢使用@HotListener模糊和聚焦,请参见stackblitz
在模糊中,您转换htmlElement的值。在Focus中解析值。请注意,您必须在第一次使用ngOnInit来显示正确的值。如果我们在输入[(ngModel)]中使用指令,则必须使用setTimeOut -else,第一次没有显示正确的值-
export class TestPipe implements OnInit {
private el: any;
constructor(private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
@HostListener("focus", ["$event.target.value"])
onFocus() {
this.el.value = this.parse(this.el.value);
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
this.el.value = this.transform(value);
}
ngOnInit()
{
setTimeout(()=>{
this.el.value = this.transform(this.el.value);
})
}
transform(value:any)
{
let minutes=+value;
let hour=Math.floor(minutes/60);
let rest=minutes%60;
return hour+":"+('00'+rest).slice(-2);
}
parse(value:any)
{
let hours=value.split(":");
return ''+((+hours[0])*60+(+hours[1]));
}
}
答案 2 :(得分:0)
您可以只使用keyUp事件,并在每次添加/删除数字时计算时间
HTML:
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
TS:
com.itextpdf.text.
这样,您不需要任何额外的代码,并且值在更改时即会更新。