为什么 [选中] 在复选框中使用时不适用于 ngModel



我在复选框中使用ngModel,遇到了[checked]="true"无法使用[(ngModel)]="select"的情况。此外,我在设置模型 select = true 的(change)上调用了一个函数,模型发生了变化,但视图没有更新。

为了解决上述两个问题,我使用了[ngModel]="true"而不是[checked],并将$event发送到我event.target.checked = true(change)函数。

最初:

<input type="checkbox" name="mycheck" [checked]="true" [(ngModel)]="works" (change)="func()">
func() {
    this.works = true;  // this updates the model but not view
}

我的尝试:

<input type="checkbox" name="mycheck" [ngModel]="true" [(ngModel)]="works" (change)="func($event)">
func(event) {
    this.works = true;  // this updates the model
    event.target.checked = true; //this updates the view
}

当我们使用带有[(ngModel)]的输入类型检查时,您唯一需要的是[(ngModel)]和一个变量。

  <input type="checkbox" [(ngModel)]="myvariable">
  <div *ngIf="myvariable">you are checked</div>
<input [(ngModel)]="works" type="checkbox"/>

这将对复选框执行双向绑定。因此,您不需要 [选中] 属性。

或者使用选中的属性而不是 ngModel,

在.html,

<input [checked]="works" type="checkbox" (change)="func($event)"/>

在 .ts 中,

works: boolean;
func(e){
  if(e.target.checked){
     this.works = true;
  }
  else{
     this.works = false;
  }
  console.log(this.works);
}

最新更新