以角度形式删除重复的属性(ngModel,值) [英] Remove duplicate attribute(ngModel, value) in angular forms

查看:88
本文介绍了以角度形式删除重复的属性(ngModel,值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个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仅表示 初始 ,日期选择器的默认值. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆