当我单击搜索链接时,我正在显示搜索输入,正在使用keyup事件从输入中获取值。但是得到的错误显示在屏幕截图中。我正在使用角度6。
零件
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-temp',
templateUrl: './temp.component.html',
styleUrls: ['./temp.component.css']
})
export class TempComponent implements OnInit, AfterViewInit {
displaySearch = false;
@ViewChild('searchValue') searchValue: ElementRef;
constructor() { }
ngOnInit() {
}
searchFunc() {
if (this.displaySearch === false) {
this.displaySearch = true;
} else if (this.displaySearch === true){
this.displaySearch = false;
}
}
ngAfterViewInit() {
fromEvent(this.searchValue.nativeElement, 'keyup').pipe(
map((event: any) => {
return (event.target).value;
})
).subscribe(res => {
console.log(res);
});
}
}
HTML
<div>
<a href="javascript:void(0)" (click)="searchFunc()">Search</a>
</div>
<ng-container *ngIf="displaySearch">
<input type="text" name="searchValue" #searchValue>
</ng-container>
您不能this.searchValue.nativeElement
在中使用ngAfterViewInit()
。其原因是,当TempComponent
加载searchValue
输入是不是在DOM
为displaySearch
是false
在那个时候。成为nativeElement
之后,您应该使用。如下更改代码。displaySearch
true
searchFunc() {
this.displaySearch = true;
setTimeout(() => {
fromEvent(this.searchValue.nativeElement, 'keyup').pipe(
map((event: any) => {
return (event.target).value;
})
).subscribe(res => {
console.log(res);
});
},3000);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句