当模型在jQuery事件中发生改变时,Angular 2不会刷新视图

Angular 2 does not refresh view when model changed from inside of jQuery event

本文关键字:Angular 新视图 刷新 改变 jQuery 模型 事件      更新时间:2023-09-26

我正在创建一个自定义搜索面板,其中包含显示搜索结果的下拉容器。

在我的控制器中我有:

export class ProductSearchComponent implements OnInit {
    public hasFocus: boolean = false;
    public results: SearchResult[] = null;
...
}

<form id="searchForm" autocomplete="off">
            <i class="glyphicon glyphicon-refresh loadingLiveSearch" id="spinnerClass" 
                [style.display]="isLoading ? '' : 'none'"></i> 
            <input type="search" #searchInput class="searchInput" id="globalSearchInput" (keydown)="textboxKeydown($event)" placeholder="start typing searched phrase..."
                   (keyup)="onChangeInputText(searchInput.value)" (change)="onChangeInputText(searchInput.value)" title="Search within VerIT Store" />
            <ul class="search-result" [class.hidden]="!(results != null && results?.length > 0 && hasFocus == true)">
                <template ngFor let-res [ngForOf]="results" let-i="index">
                    <li></li>
                    <li *ngIf="i < 5"> {{ hasFocus ? "1" : "0" }}
                        <a [routerLink]="getProductLink(res)" (click)="hideList()">
                            <h3 [innerHtml]="markFoundPattern(res.name)"></h3></a>
                        <h4>{{res.desc}}</h4>
                    </li>
                </template>
            </ul>
        </form>

,因为我需要隐藏结果窗格,当有人点击页面上的任何地方,我有以下代码在控制器:

public ngOnInit(): void {
    // this has to be uncommented to make things work.
    //window.setInterval(() => { }, 100);
    $("#globalSearchInput").focusout(() => {
        this.hasFocus = false;
    });
    $(".search-result, #globalSearchInput").focusin(() => {
        this.hasFocus = true;
    });
}

你能想象我花了4个小时试图在我的代码中找到一个错误,并解释为什么视图没有重新绑定更新的hasFocus值吗?

当我开始尝试在windows中运行计数器时。setInterval来确保我还没有失去理智,然后,其他东西开始工作了

在and中,我不得不离开并清空window.setInterval(() => { }, 100),以确保当jQuery在事件回调中改变值时,视图也会得到更新。

但这对我来说是一种欺骗。

你能给我一个合适的方法来通知angular更新视图吗?

我已经阅读http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html,我试图使用ChangeDetectorRef这样:

constructor(
    @Inject(ChangeDetectorRef) private ref: ChangeDetectorRef
) { }
public ngOnInit(): void {
        //window.setInterval(() => { }, 100);
        $("#globalSearchInput").focusout(() => {
            this.hasFocus = false;
            this.ref.markForCheck();
        });
        $(".search-result, #globalSearchInput").focusin(() => {
            this.hasFocus = true;
            this.ref.markForCheck();
        });
}

…但是,是的,它也没有工作。

的想法,好吗?:)

我试着看看是什么问题,但无法找出为什么它不与 JQuery 工作。

但是,如果您想以 Angular2 的方式完成,您可以使用 (focus) (blur) input control

无需Jquery

<input type="search" #searchInput (focus)="focusIn()" (blur)="focusOut()" ...> 
focusIn(){
   this.hasFocus = false;
}
focusOut(){
   this.hasFocus = true;
}