0

I'd like to perform an action (submit the form, basically) when a string entered in an input field reaches a given length, using Angular2. I tried using Angular2's Controls but it didn't seem to be meant for that.

I could do it using jQuery or vanilla Javascript but I was wondering if there was a more "Angular2" way to do it.

<input type="text" value="{{userInput}}" class="form-control">
// When userInput > 3, submit form

This framework being relatively new, I cannot find any solution on the Internet, although it is probably very simple. Does anyone have an idea ?

Thank you.

  • Bind, `ng-change` directive and invoke `submit-handler` when test is passed! – Rayon Jun 13 '16 at 20:05
  • Sorry I should have underlined the fact that I'm looking for an Angular2 solution. –  Jun 13 '16 at 20:08
  • @ojathelonius I think the Angular 2 equivalent is the interface "OnChange" in @angular/core. – Katana314 Jun 13 '16 at 20:10
  • Figured it out right here : http://stackoverflow.com/a/34615922/6380030 To watch an input field, just add a ngModel to it then bind ngModelChange to a function in your Component. Easy ! –  Jun 13 '16 at 20:45

1 Answers1

0

You could associate a control on the input and subscribe on its valueChanges property.

Here is a sample:

@Component({
  (...)
  template: `
    <input type="text" value="{{userInput}}"
           class="form-control"
           [ngFormControl]="ctrl">
  `
})
export class SomeComponent {
  constructor() {
    this.ctrl = new Control();
    this.ctrl.valueChanges
          .filter((value) => {
            return (value.length > 3);
          })
          .subscribe((value) => {
            // do something
          });
  }
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360