首页 > 解决方案 > 复选框加载但未点击 HTML Angular

问题描述

有一个奇怪的问题,复选框被加载了 id 和值但没有被点击。也没有显示错误。

<button [popover]="columnConfigJobDetails"><span class="icon-cog"></span></button>  
    <popover-content #columnConfigJobDetails [closeOnClickOutside]="true">
        <ng-container *ngFor='let col of columnDropdownStates'><form>
            <label *ngIf='col' class="checkbox ">
                <input type="checkbox" id={{col.field}} [checked]="col.visible" 
                 name={{col.header}} (change)="onColumnChange($event)"/>
                <span class="checkbox__input"></span>
                <span class="checkbox__label">{{col.header}}</span>
            </label></form>
        </ng-container>
    </popover-content>

我的 Angular/typescript 代码看起来像一个对象数组。

this.columnDropdownStates -:

     0: {header: "Name", field: "name", visible: true}
     1: {header: "Devices Enabled", field: "enabledDeviceNumber", visible: true}
     2: {header: "Description", field: "description", visible: true}

新更新 - 我确实收到此错误,但不确定它是什么意思

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: undefined'. Current value: 'ngIf: true'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?

标签: htmlangularngfor

解决方案


There are two possible fixes,

  1. If you are initializing or assigning your *ngIf values on the ngOnInit() you have to move it to ngAfterViewInit() as at this point the change detection doesn’t work on the ngOnInit(). Another reason is, in most cases, your view is probably not initialized in the ngOnInit().

  2. If you are using Angular version of above 8, you might have to set a static flag while creating your @ViewChild as it is mandatory from v8. For example,

    @ViewChild(TemplateRef, { static: }) templateRef : TemplateRef;

The true or false values depends on the following situations,

{ static: true } if you are accessing ViewChild in ngOnInit

{ static: false } if you are accessing in ngAfterViewInit. This should also be used in your scenario where you are using NgIf, NgFor, NgSwitch or other structural directives.

Note: In Angular 9, the static flag is defaulted to false.

For more details please refer this official discussion.


推荐阅读