属性目标确实存在于对象上

时间:2018-07-03 03:05:59

标签: angular typescript

ngAfterViewInit() {
        const searchSource = document.getElementById("search-box");      
        const inputStream = fromEvent(searchSource, "input");
        inputStream
            .pipe(
            map(event => (<HTMLInputElement>event.target).value.trim()),
                debounceTime(500),
                distinctUntilChanged(),
        )
            .subscribe(() => {
                let updatedValue = encodeURI((searchSource as HTMLInputElement).value);

                if (updatedValue.length >= 2) {
                    this.listSearchResults(updatedValue);
                    this.showProgressbar = true;
                } else {
                    this.showDropDown = false;
                    this.noMatchesFound = false;
                }
            });
    }
尝试在上述代码中的事件上访问目标时,Angular中的

TypeScript显示错误“对象上确实存在属性目标”。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您应将事件的类型指定为KeyboardEvent / MouseEvent /两者的结合,这样才能满足typescript的输入

map((event: KeyboardEvent|MouseEvent) => (<HTMLInputElement>event.target).value.trim()), 

在这种情况下,我建议您在元素上使用#templateVariable,并使用@ViewChild装饰器保留该DOM

答案 1 :(得分:1)

document.getElementById中不需要AngularformControl可以轻松完成。

HTML

<input placeholder="Enter a value" [formControl]="searchCtrl"/>

TS

searchCtrl: FormControl = new FormControl();

this.searchCtrl.valueChanges
    .debounceTime(500)
    .distinctUntilChanged()
    .subscribe(val => {
        // Do whatever you want
    });