【问题标题】:How do I fix a TypeError regarding a ViewChild element that actually works?如何修复关于实际工作的 ViewChild 元素的 TypeError?
【发布时间】:2022-07-21 15:55:07
【问题描述】:

这是复选框所在的 HTML 组件

 <mat-checkbox class="dashboard-content-custom-select-option" id="dashboard-all-checkbox" #allSelector [indeterminate]="someCheckboxesActive()" [checked]="allCheckboxesActive()" (click)="toggleAllSelection($event)">Alle </mat-checkbox>
如果选中所有上面的复选框,则选中 Select all Mat-Checkbox。如果在某些复选框留空并且所有复选框都被选中时单击,也会检查它。

export class DashboardContentComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('dashboard-all-checkbox') allSelect: MatCheckbox;

toggleAllSelection(event) { // toggle checkbox is controlled from here
    console.log(this.allSelect);
    if ( event.currentTarget.id === 'dashboard-all-checkbox' && this.selectedValues.length === 6) {
      this.dashboardContentForm.get('dashboardContentValue').setValue([]); 
      this.allSelect.checked = false; // unchecks the checkbox
    } else if ( (this.selectedValues.length < 6  && event.currentTarget.id === 'dashboard-all-checkbox') )  {
      this.dashboardContentForm.get('dashboardContentValue').setValue(
         [ ...this.displayDashboardContentValues.map((dv) => dv.key), ...[0]]
      );
      this.allSelect.toggle(); //checks the checkbox
    }
  }
}
在这个 TS 文件中,上面的 6 个复选框必须全部处于活动状态才能使 Select All 复选框处于活动状态。 否则,如果少于 6 个处于活动状态,则它变得不确定。

确切地说,一切正常。 然而,唯一的问题是我得到了 TypeErrors 虽然复选框做了它应该做的任何事情。如果使用复选框的 id,一切都很好(在我的情况下,这是唯一可行的方法)。如果我使用#allSelector,那就不同了。 如何防止发生这些错误? 此外,您可以忽略下拉菜单中的灰色突出显示,它不相关。

如果单击并选中全选复选框

如果选中了全选复选框并且未选中

【问题讨论】:

    标签: angular typescript checkbox error-handling viewchild


    【解决方案1】:

    您可以阅读 ViewChild 应该指向 #allSelector(本地模板变量)而不是 id="dashboard-all-checkbox"(id 选择器)。

    通过将 ViewChild 更改为查找 allSelector 应该可以解决此问题。

    @ViewChild('allSelector') allSelect: MatCheckbox;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      相关资源
      最近更新 更多