0

有人可以帮我找出为什么在我提交表单后我的值最终返回小写字母

从 '@angular/forms' 导入 { FormGroup, FormControl, Validators };

这是我的代码

组件.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();
}

大写的.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();}
}

组件.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>

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

4

1 回答 1

1

The angular form control listens to the 'input' event of the element. It seems your directive does the same but after the directive updates the value, ngControl doesn't know about it till the next input event happens. So at the end of the data the form control always have the value entered . You can dispatch an 'input' event from the directive but I doubt it will go in a loop. You can try listening to keydown/keyup event or something directive and emitting 'input' event after that.

When directives are used with form controls I think it is better to extend ControlValueAccessor for your directive. Please see some of the answers to the question below for some good examples :-

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

于 2017-07-17T01:12:47.203 回答