Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 510
Luka Šilje Avatar asked Mar 12 '23 12:03

Luka Šilje


1 Answers

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

like image 75
Mark Rajcok Avatar answered Mar 20 '23 23:03

Mark Rajcok