How to call function on input text change in angular 2

Usf Noor picture Usf Noor · Jan 3, 2018 · Viewed 16.2k times · Source

I want to call the type script function on input change of text box, and its working for me. But it call on every change, I want to call when the minimum number of character in the text box are 5.

export class StudentMaintenanceComponent implements OnInit {
    @Component({
        selector: 'app-student-management',
        template: `<input placeholder="" class="form-control" type="text" [maxlength]="5" (input)="SearchData($event.target.value)">`,
        styleUrls: ['./app-student-management.css']
    })

    SearchData(_no: string) { // should be called when minimum no of character are 5 in the text field.
        console.log(_no);
    }
}

Answer

Arshmeet picture Arshmeet · Jan 4, 2018

You can write something like this

(input)="$event.target.value.length > 5 && SearchData($event.target.value)"

You can also use template reference variable like this

<input placeholder="" #textInput class="form-control" type="text" [maxlength]="5" (input)="textInput.value.length > 5 && SearchData(textInput.value)">