使用ngIf检查表单控件,抛出了ExpressionChangedAfterItHasBeenCheckedError

时间:2019-02-04 14:56:17

标签: angular typescript ngrx

我有一个Angular应用程序,并在页面页眉(基本上是带有输入文本的表单)中实现了搜索栏。我想在输入中包含一个“ x”按钮,以便可以重置其文本。仅当输入包含文本时,该按钮才出现。我发现的第一个解决方案是将输入类型更改为“搜索”,但这并没有达到我的预期。之后,我手动添加了按钮并使用* ngIf指令检查formControl是否具有任何值。

<button *ngIf="searchTerm.value" pButton type="reset"
        class="iwp-icon-gen_close_l reset-button"
        [izDisabled]="isDisabled$ | async"
        (click)="resetSearchTerm()"
></button>

在我的组件中,代码如下:

// The user input in the full text search input field.
searchTerm = new FormControl('');

ngOnInit() {
    this.filterService.filter$
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(filter => this.searchTerm.setValue(filter.searchTerm));
}

页面加载时,它会抛出ExpressionChangedAfterItHasBeenCheckedError,我知道可以通过使用setTimeOut(fn,0)将代码封装在ngOnInit中来解决,但是我试图找出一种“干净”的方法。有人可以帮我吗?

0 个答案:

没有答案
相关问题