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
pixelbits has provided a great solution but it does not work in the latest version of Angular (v4.3.1) as directives are depreciated from component. My solution is based on his answer only but works with the latest
I am providing a generic solution with custom attribute directive with a boolean input which will covert the input to Uppercase if it is true.
upper-case.directive.ts :
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[UpperCase]',
host: {
'(input)': 'toUpperCase($event.target.value)',
}
})
export class UpperCaseTextDirective {
@Input('UpperCase') allowUpperCase: boolean;
constructor(private ref: ElementRef) {
}
toUpperCase(value: any) {
if (this.allowUpperCase)
this.ref.nativeElement.value = value.toUpperCase();
}
}
Here is the corresponding App component with the template.
app.ts
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {UpperCaseTextDirective} from './upper-case.directive'
@Component({
selector: 'my-app',
template: `
Hello {{name}}
Auto Capitalize True:
Auto Capitalize False:
`,
})
export class App {
name:string;
allowEdit:boolean;
constructor() {
this.name = `Angular! v${VERSION.full}`;
this.allowEdit= false;
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App,UpperCaseTextDirective ],
bootstrap: [ App ]
})
export class AppModule {}
Here is a Plnkr which demonstrate this.