英文:
Angular Material and input type 'time', value property vs ngModel
问题
我正在尝试将传入的日期对象拆分为两个单独的mat-form-fields。
首先,我创建了DatePicker并给它正确的默认值:
<mat-form-field>
<mat-label>Datum laden: </mat-label>
<input matInput [matDatepicker]="loadPicker" placeholder="Choose a date" [(ngModel)]="data.mission.loadDate">
<mat-datepicker-toggle matSuffix [for]="loadPicker"></mat-datepicker-toggle>
<mat-datepicker #loadPicker></mat-datepicker>
</mat-form-field>
当我到达时间元素时,情况变得有点棘手。Angular Material似乎没有处理时间的方法。这意味着我必须退回到旧的方法,只需将输入字段的类型设置为"time"。在视觉上它工作正常,但使用value属性似乎不起作用。
有人能解释一下为什么使用ngModel可以工作,而另一种方法不行吗?
工作版本:
<mat-form-field>
<mat-label>Tijd laden: </mat-label>
<input matInput type="time" [(ngModel)]="test">
</mat-form-field>
其中"test"是:
test = `${this.mission.loadDate.getHours()}:${this.mission.loadDate.getMinutes()}`;
不工作的版本:
<mat-form-field>
<mat-label>Tijd laden: </mat-label>
<input matInput type="time" [value]="`${data.mission.loadDate.getHours()}:${data.mission.loadDate.getMinutes()}`">
</mat-form-field>
考虑到type="time"由浏览器处理,我认为这两种方法都应该起作用。
英文:
I am trying to split my incoming date object in 2 seperate mat-form-fields.
Firstly I create the DatePicker and give it the correct default value:
<mat-form-field>
<mat-label>Datum laden: </mat-label>
<input matInput [matDatepicker]="loadPicker" placeholder="Choose a date" [(ngModel)]="data.mission.loadDate">
<mat-datepicker-toggle matSuffix [for]="loadPicker"></mat-datepicker-toggle>
<mat-datepicker #loadPicker></mat-datepicker>
</mat-form-field>
When I get to the time element it gets a bit tricky. Angular material doesn't seem to have a method of handling time. That means I have to revert back to the older method and just give my input field the type="time". Visually it works, giving it a value however doesn't seem to work when using the value property.
Could someone explain to me why using ngModel works but the other method doesn't?
Working version:
<mat-form-field>
<mat-label>Tijd laden: </mat-label>
<input matInput type="time" [(ngModel)]="test">
</mat-form-field>
test being:
test = `${this.mission.loadDate.getHours()}:${this.mission.loadDate.getMinutes()}`;
non-working version:
<mat-form-field>
<mat-label>Tijd laden: </mat-label>
<input matInput type="time" value=`${data.mission.loadDate.getHours()}:${data.mission.loadDate.getMinutes()}`>
</mat-form-field>
Considering type="time" is handled by the browser. I would assume that both methods should work.
答案1
得分: 4
实际上,value
是一个HTML属性,需要使用表达式绑定来绑定HTML属性。而[value]
是一个DOM属性,不需要表达式绑定,另一方面,您不需要使用getHours和getMinutes。您可以使用Angular提供的日期过滤器。只需查看这个示例。
英文:
actually <code>value</code> is an HTML attribute and for binding with HTML attribute you need to use expression binding. while <code>[value]</code> is a DOM property that doesn't need expression bindings and on another side, you don't need to use getHours and getMinutes. you can use a date filter that is provided by angular. just see this example
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论