【问题标题】:Angular 2 attribute directive to modify the input host text and valueAngular 2 属性指令来修改输入主机文本和值
【发布时间】:2016-10-13 22:57:16
【问题描述】:

我需要一个属性指令,它将输入格式化为 dd-mm-yyyy 并将其作为文本值并根据 javascript 日期作为值。在 rc.3 我使用了ngFormControl.valueAccessor.writeValue() 和其他一些方法。现在似乎 NgFormControl 在发布版本中消失了。我现在应该使用什么?这是我之前在做的:

<input type="text" format-date2 [ngFormControl]='formControls.dateOfMarriage'>

import {Directive, ElementRef} from '@angular/core';
import {NgFormControl} from '@angular/common';

@Directive({
selector: '[format-date2]',
host: {
  '(input)': 'onInputChange()',
  'placeholder': 'dd-mm-yyyy',
 },
})
export class FormatDate2 {

viewValue;
modelValue;
currentValue = '';
el: HTMLInputElement;

constructor(private model: NgFormControl, private elementRef: ElementRef) {
  this.el = elementRef.nativeElement;
}

ngOnInit() {
 if (this.model.control.value) {
  let d = new Date(this.model.control.value);
  let s = this.pad(d.getDate()) + '-' + this.pad(d.getMonth() + 1) + '-' + d.getFullYear();
  this.model.valueAccessor.writeValue(s);
  }
}

pad(n) {
  return n < 10 ? '0' + n : n;
}

onInputChange() {
  let i = this.el.selectionEnd - this.el.value.length;
  this.format(this.el.value);
  i = this.viewValue.length + i;
  this.model.control.updateValue(this.modelValue);
  this.model.valueAccessor.writeValue(this.viewValue);
  this.el.setSelectionRange(i, i);
  return false;
}

format(val) {
// some code
//   this.modelValue = 'some value';
//   this.viewValue = 'another value' 
}

}

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:
    • 而不是NgFormControl 类使用NgControl / @angular/forms
    • 使用[formControl],而不是[ngFormControl] 指令。

    您还需要确保 @NgModule.imports: [ ReactiveFormsModule ] 进入声明使用表单的组件的任何模块。这是用于使用反应式表单,即 FormControl/FormGroup,但模板表单,只需使用 @987654329 @。您的示例虽然看起来像是使用反应形式。但您的指令也适用于模板表单。

    【讨论】:

    • 具体我使用了 NgControl.control.setValue() 和 NgControl.valueAccessor.writeValue()
    猜你喜欢
    • 2023-03-27
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2018-02-27
    • 2016-08-14
    • 2018-09-26
    • 2016-10-02
    相关资源
    最近更新 更多