首页 > 解决方案 > 对象上确实存在属性目标

问题描述

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 在尝试访问上述代码中的事件目标时显示错误“对象上确实存在属性目标”。请问有什么想法吗?

标签: angulartypescript

解决方案


您应该将事件类型指定为KeyboardEvent//MouseEvent两者的联合,这将满足typescript

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

相反,我建议您#templateVariable在这种情况下使用 on 元素,并使用@ViewChild装饰器来保留DOM.


推荐阅读