ViewChild 的元素引用未定义
Element reference of ViewChild is undefined
看看下面的代码。
// ...
@ViewChild('searchBar', {static: false}) searchBar: IonSearchbar;
@ViewChild('locations', {static: false}) locationsList: IonList;
// ...
ngAfterViewInit() {
this.searchBarInputSub =
this.searchBar.ionInput
.pipe(
pluck('target', 'value'),
debounceTime(400),
distinctUntilChanged()
).subscribe(this.onNewLocation);
console.log(this.locationsList);
}
onNewLocation(prefix: string) {
console.log(this.locationsList);
}
为什么 onNewLocation
打印 undefined
?请注意,ngAfterViewInit
打印对象描述...
当您订阅 observable 时语法不正确,subscribe(this.onNewLocation)
行中的 this
也不是您认为的那样。
进行以下更改:
ngAfterViewInit() {
this.searchBarInputSub =
this.searchBar.ionInput
.pipe(
pluck('target', 'value'),
debounceTime(400),
distinctUntilChanged()
)
.subscribe((location: string) => this.onNewLocation(location));
}
看看下面的代码。
// ...
@ViewChild('searchBar', {static: false}) searchBar: IonSearchbar;
@ViewChild('locations', {static: false}) locationsList: IonList;
// ...
ngAfterViewInit() {
this.searchBarInputSub =
this.searchBar.ionInput
.pipe(
pluck('target', 'value'),
debounceTime(400),
distinctUntilChanged()
).subscribe(this.onNewLocation);
console.log(this.locationsList);
}
onNewLocation(prefix: string) {
console.log(this.locationsList);
}
为什么 onNewLocation
打印 undefined
?请注意,ngAfterViewInit
打印对象描述...
当您订阅 observable 时语法不正确,subscribe(this.onNewLocation)
行中的 this
也不是您认为的那样。
进行以下更改:
ngAfterViewInit() {
this.searchBarInputSub =
this.searchBar.ionInput
.pipe(
pluck('target', 'value'),
debounceTime(400),
distinctUntilChanged()
)
.subscribe((location: string) => this.onNewLocation(location));
}