以角度形式删除重复的属性(ngModel,值) [英] Remove duplicate attribute(ngModel, value) in angular forms
问题描述
我制作了一个 DatePickerDirective
,它按要求工作正常.但是为了同步该指令所在的特定输入字段的值,我必须同时使用 value 和 ngModel 属性.我希望只使用 ngModel 如何优雅地实现这一点.
I have made a DatePickerDirective
which is working fine as required. But in order to sync the value of the particular input field on which this directive sits, I have to use value and ngModel attribute both. I wish to use only ngModel how can this be achieved gracefully.
表单元素
<input appDatePicker type="text" required name="title" value="{{holiday.off_date}}" [(ngModel)]="holiday.off_date" class="form-control"
placeholder="01/01/2018">
组件文件
export class HolidayCreateComponent implements OnInit, OnDestroy {
holiday = new HolidayModel('', '');
}
模型文件
export class HolidayModel {
constructor(public occasion: string, public off_date: string) {
}
}
指令文件
import {Directive, ElementRef, forwardRef, OnInit} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
declare const $: any;
@Directive({
selector: '[appDatePicker]',
providers: [{
provide: NG_VALUE_ACCESSOR, useExisting:
forwardRef(() => DatePickerDirective),
multi: true
}]
})
export class DatePickerDirective implements OnInit, ControlValueAccessor {
value: string;
constructor(private el: ElementRef) {
}
ngOnInit() {
$(this.el.nativeElement).datepicker({
autoclose: true,
todayHighlight: true,
format: 'dd/mm/yyyy'
}).on('change', e => this._onChange(e.target.value));
}
private _onChange(_) {
}
private _onTouched(_) {
}
registerOnChange(fn: any): void {
this._onChange = fn;
}
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
}
writeValue(val: string): void {
this.value = val;
}
}
问题是每当我尝试从组件操作日期字段的值时,我都需要同时使用 value 和 ngmodel.我觉得这是不对的可以改进.有什么我忘记的吗.
The problem is whenever i try to manipulate value of date field from component i need use both value and ngmodel. I think this is not right can be improved. Is there anything which i forgot.
注意:只有在使用指令时才需要值和 ngModel.如果输入没有指令,那么 ngModel 工作得很好.我希望具有指令的元素具有相同的行为.
NOTE: the value and ngModel is required only where directive is used. If the input has no directive then ngModel works just perfect. I want the same behavior for the element with directive.
推荐答案
value
仅表示 initial,日期选择器的默认值.ngModel
是双向绑定对象,它包含用户选择日期后的数据.你的代码很好.
value
simply means the initial, default value of the datepicker. ngModel
is the two-way bound object that has your data afther the user pick's the date. Your code is fine as it is.
这篇关于以角度形式删除重复的属性(ngModel,值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!