首页 > 解决方案 > 无法读取未定义的属性“valueChanges”

问题描述

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

hmtl:

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

在 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)
      }
    }) 
  }

我得到的错误

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)

标签: angularrxjs

解决方案


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

解释

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


推荐阅读