Angular2 – Textarea validation how to force blur

My form is submitted via the Enter key. The value of the textarea is null, since the focus is still on the textarea.

Is there a way to force blur on the textarea, or is there any more graceful approach?

3
Leave a Reply

avatar
3 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

To blur a DOM form element, use a local template variable in combination with @ViewChild to get an “Angular wrapped” reference to the textarea. Then use Renderer to blur, after unwrapping it with nativeElement:

@Component({
  selector: 'my-app',
  template: `
    <form>
      <textarea #textArea [(ngModel)]="text" (keyup.enter)="submit()"></textarea>
    </form>
  `
})
export class AppComponent {
  text = "";
  constructor(private renderer:Renderer) { console.clear(); }
  @ViewChild('textArea') textArea:ElementRef;
  submit() {
    this.renderer.invokeElementMethod(
      this.textArea.nativeElement, 'blur', []);
  }
}

Plunker

Jason
Guest

You can do 3 things here to validate before submit –

1) Create a function in your component that validates your textarea and call it in your submit function.
Like this —

onSubmit(){
    isTextAreaValid = this.validateTextArea();
    if(isTextAreaValid){
         //submit the data
    }
}

2) Or create a property named ‘isTextAreaValid’ to check, like this —

<form *ngIf="active" (ngSubmit)="onSubmit() && isTextAreaValid" #heroForm="ngForm">

3) Or do just like this —

<form #heroForm="ngForm" (ngSubmit)="heroForm.form.valid && onSubmit()">

Jason
Guest

I’m assuming you are using ngSubmit directive to submit form. I’d prefer you to check validity of form before calling submit method of the form. Make sure you should have required attribute on the fields which are required before submit. <form #myForm="ngForm" (ngSubmit)="myForm.valid && submit()"> So basically before submitting form it will check validity of form, if yes then only it will call submit method. Edit You could also do check form validity from your angular component also inside submit method. HTML <form #myForm="ngForm" (ngSubmit)="&& submit()"> Component submit(){ if(this.myForm.valid){ console.log('MyForm is valid'); //do make ajax or call action to submit… Read more »