无法读取未定义的属性“valueChanges”

S4L*_*L4H 5 rxjs angular

我正在尝试在 ViewChild 类型 NgModel 上实现 valueChanges,但在 OnInit、AfterViewInit 或 AfterContentChecked 中不断收到相同的错误

嗯:

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

在 ts 文件上我做了

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)
      }
    }) 
  }
Run Code Online (Sandbox Code Playgroud)

我得到的错误

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)
Run Code Online (Sandbox Code Playgroud)

Edi*_*son 6

请尝试这样改变@ViewChild('filterInout',{static: true}) filterInout: NgModel

解释

如果设置static false,则组件始终会在视图初始化后及时为ngAfterViewInit/ngAfterContentInitcallback函数进行初始化。这是与旧配置的标准情况的匹配,只不过现在是强制的。如果static设置为true,则初始化将在视图初始化时进行(ngOnInitfor @ViewChild@ContentChild)。