Angular 2 |提交表单时显示小写值

Angular 2 | Showing lowercase value when form is submitted

有人可以帮我找出为什么在我使用

提交表单后我的值最后返回小写吗

import { FormGroup, FormControl, Validators } from '@angular/forms';

这是我的代码

component.ts

import { Component, Directive, OnInit, OnDestroy} from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

import {UppercaseDirective} from '../uppercase.directive';

@Component({  selector: 'app-storageentry',
  templateUrl: './storageentry.component.html',
  styleUrls: ['./storageentry.component.css']
})

export class StorageentryComponent implements OnInit, OnDestroy {
  storageForm: FormGroup;

   private initForm(){
    let storageDescription: string;

    //pass the formControl specified by '' to use in HTML
    this.storageForm = new FormGroup({
      description: new FormControl(storageDescription, Validators.required)
    })
  }
}

ngOnInit() {
    this.initForm();
}

onSubmit(){
  this.storageEntryService.addStorage(this.storageForm.value);
   this.storageForm.reset();
}

uppercase.directives.ts

import { Directive, HostListener, Renderer, ElementRef } from '@angular/core';
@Directive({
    selector: '[uppercase]'
})
 export class UppercaseDirective{

constructor(
    private renderer: Renderer,
    private el: ElementRef
){}

@HostListener('input') input() {
this.el.nativeElement.value=this.el.nativeElement.value.toUpperCase();}
}

component.html

<div class="form-group input-holder">
  <label class="col-lg-2">Description</label>
  <div class="col-lg-4">
    <small [ngClass]="{'prompterror': storageForm.controls.description.valid || storageForm.controls.description.pristine}">
     *required
    </small>
    <input type="text" class="input-field" placeholder="Description" formControlName="description" uppercase>
  </div>
</div>

这是输出 |如您所见,它在我的数据末尾显示小写值。

angular表单控件监听元素的'input'事件。看起来你的指令做同样的事情但是在指令更新值之后,ngControl 在下一个输入事件发生之前不知道它。所以在数据的末尾,表单控件总是有输入的值。您可以从指令中分派 'input' 事件,但我怀疑它会进入循环。您可以尝试收听 keydown/keyup 事件或其他指令,然后发出 'input' 事件。

当指令与表单控件一起使用时,我认为最好为指令扩展 ControlValueAccessor。请查看下面问题的一些答案以获得一些很好的例子:-

How to convert input value to uppercase in angular 2 (value passing to ngControl)