angular - 无法读取未定义的属性“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)
解决方案
请尝试像这样改变@ViewChild('filterInout',{static: true}) filterInout: NgModel
解释
如果您设置static
false,组件总是在视图初始化后及时为ngAfterViewInit/ngAfterContentInitcallback
函数初始化。这是与旧配置的标准情况的匹配,只是现在是强制的。如果static
设置为true,则初始化将在视图初始化 (ngOnInitfor @ViewChild
和@ContentChild
) 处进行。
推荐阅读
- javascript - 如何获取我在柏树字段下插入的文本长度
- python - 不允许使用饼干机械汤
- plot - 在 Maple 中线性化,绘制微分方程系统的分岔?
- mysql - sql根据父表求和
- python - 如何从 rsa 加密消息中获取数字
- javascript - 如何使用 js 以编程方式在另一个页面上读取 chrome://discards 的内容?
- react-native - NativeModule:AsyncStorage 与 Expo 为空
- flutter - 根据条件禁用 Flutter 中的图标按钮
- kotlin - 在 Kotlin 中定义枚举结构?
- excel - 你能帮我吗,我怎样才能在excel散点图中添加垂直线