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

后端 未结 10 695
不知归路
不知归路 2020-11-28 10:31

I am trying to validate the input fields using ngControl\'s value in angular 2. i need to validate that the user enters the value in upper case always.

Now we need

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 10:59

    I would create a custom implementation of ControlValueAccessor. The latter would correspond to a directive that would listen the input event of the host. This way you will be able to put in uppercase what you user fills. The control will automatically contains the value in uppercase.

    Here is the implementation:

    @Directive ({
      selector: 'input[uppercase]',
      // When the user updates the input
      host: { '(input)': 'onChange($event.target.value.toUpperCase())' }
    })
    export class UppercaseValueAccessor extends DefaultValueAccessor {
      (...)
    
      // When the code updates the value of the
      // property bound to the input
      writeValue(value:any):void {
        if (value!=null) {
          super.writeValue(value.toUpperCase());
        }
      }
    }
    

    Don't forget to register this custom value accessor in the directive providers. This way your custom value accessor will be used instead of the default one.

    const UPPERCASE_VALUE_ACCESSOR = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => UppercaseValueAccessor), multi: true});
    
    @Directive ({
      providers: [ UPPERCASE_VALUE_ACCESSOR ],
      (...)
    })
    export class UppercaseValueAccessor ...
    

    And add the directive in the directives attribute of the component where you want to use this approach.

    See this class for more details:

    • https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts

    This link could give additional hints (see section "NgModel-compatible component):

    • http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/

提交回复
热议问题