Cannot read property 'valueChanges' of undefined

Viewed 5948

I am trying to implement the valueChanges on a ViewChild type NgModel but I keep getting the same error in OnInit, AfterViewInit or AfterContentChecked

hmtl:

<form action="">
  <input type="text" [(ngModel)]="searchTerm" name="searchTerm" #filterInput="ngModel"  >
  <button class="sp_search_btn"  style="width: 100%;"></button>
</form> 

On ts file I did

export class IndexComponent implements OnInit{
  @ViewChild('filterInput',{static: false}) filterInput: NgModel
  searchTerm: string;

  ngOnInit() {
    this.filterInput
    .valueChanges
    .pipe(
      debounceTime(500),
      distinctUntilChanged()
    )
    .subscribe(term => {
      if(term){
        this.getFaqBySearchTerm(term)
      }
    }) 
  }

the error I get

index.component.html:37 ERROR TypeError: Cannot read property 'valueChanges' of undefined
at IndexComponent.ngOnInit (index.component.ts:70)
at checkAndUpdateDirectiveInline (core.js:24503)
at checkAndUpdateNodeInline (core.js:35163)
at checkAndUpdateNode (core.js:35102)
at debugCheckAndUpdateNode (core.js:36124)
at debugCheckDirectivesFn (core.js:36067)
at Object.updateDirectives (index.component.html:37)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:36055)
at checkAndUpdateView (core.js:35067)
at callViewAction (core.js:35433)
1 Answers

please try changing like this @ViewChild('filterInout',{static: true}) filterInout: NgModel

Explanation

If you set static false, the component ALWAYS gets initialized after the view initialization in time for the ngAfterViewInit/ngAfterContentInitcallback functions. This is the matching with the standard case of the old configuration, except that it is now forced. If static is set true, the initialization will take place at the view initialization (ngOnInitfor @ViewChild and @ContentChild).

Related