13

I have forms in my Angular 2 application that uses ngControl. Example:

<label for="login-field-inputLogin" class="sr-only">Login</label>
<input 
    [(ngModel)]="login" 
    id="login-field-inputLogin" 
    class="form-control" 
    placeholder="Login" 
    ngControl="loginCtrl" 
    #loginCtrl="ngForm" 
    type="text" 
    required />
<div [hidden]="loginCtrl.valid || loginCtrl.pristine" class="alert alert-danger">Login is required</div>

Unfortunately on IE 11, when there is a placeholder, the message "Login is required" is diplayed as soon as the field gets focus.

I found a solution to this issue for AngularJS. See AngularJS / How to prevent IE triggering automatically inputs validation?

How woudl one adapt this solution to Angular 2?

Community
  • 1
  • 1
jpm
  • 131
  • 1
  • 4

3 Answers3

0

You can modify this approach to solve this problem.

Possible solution:

<label for="login-field-inputLogin" class="sr-only">Login</label>
<input 
    validate-onblur     <---    directive, see below
    [(ngModel)]="login"
    id="login-field-inputLogin"
    class="form-control"
    placeholder="Login"
    ngControl="loginCtrl"
    #loginCtrl="ngModel"
    type="text"
    required />
<div [hidden]="loginCtrl.valid || loginCtrl.pristine" class="alert alert-
danger">Login is required</div>

Directive code:

@Directive({
    selector: '[validate-onblur]',
    host: {
        '(focus)': 'onFocus($event)',
        '(blur)' : 'onBlur($event)'
    }
})
export class ValidateOnBlurDirective {

    private hasFocus = false;

    constructor(public formControl: NgControl) {
    }

    // mark control pristine on focus
    onFocus($event) {
        this.hasFocus = true;
        this.formControl.control.valueChanges
            .filter(() => this.hasFocus)
            .subscribe(() => {
                this.formControl.control.markAsPristine();
            });
    }

    // mark control  dirty on focus lost
    onBlur($event) {
        this.hasFocus = false;
        this.formControl.control.markAsDirty();
    }
}
Community
  • 1
  • 1
Roman Kondakov
  • 111
  • 1
  • 3
0

Just replace the placeholder as below: [placeholder]=" 'Full Name' "

arun mohan
  • 11
  • 3
0

using [placeholder] instead of placeholder is working. but if you're using i18n tools you run into the next issue, the placeholder text is no longer parsed from the extraction tool and the translations for the placeholder is no longer working :D