Angular 在复选框中使用时,[选中]为什么不能与ngModel一起使用?

Angular 在复选框中使用时,[选中]为什么不能与ngModel一起使用?,angular,Angular,我在复选框中玩ngModel,遇到了这样一种情况:我发现,[checked]=“true”没有使用[(ngModel)]=“select”。另外,我在(change)上调用了一个函数,我将模型设置为select=true,模型已更改,但视图未更新 为了解决上述两个问题,我使用了[ngModel]=“true”而不是[checked],并将$event发送到(change)上的函数,我在那里执行了event.target.checked=true 最初: <input type="check

我在复选框中玩ngModel,遇到了这样一种情况:我发现,
[checked]=“true”
没有使用
[(ngModel)]=“select”
。另外,我在
(change)
上调用了一个函数,我将模型设置为select=true,模型已更改,但视图未更新

为了解决上述两个问题,我使用了
[ngModel]=“true”
而不是
[checked]
,并将
$event
发送到
(change)
上的函数,我在那里执行了
event.target.checked=true

最初:

<input type="checkbox" name="mycheck" [checked]="true" [(ngModel)]="works" (change)="func()">

func() {
    this.works = true;  // this updates the model but not view
}

func(){
this.works=true;//这会更新模型,但不会更新视图
}
我的尝试:

<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
}

职能(活动){
this.works=true;//这将更新模型
event.target.checked=true;//这将更新视图
}

当我们使用输入类型检查[(ngModel)]时,您只需要[(ngModel)]和一个变量

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

你检查过了

试试这个。工作=检查过但没有运气@MukulSharma@MohitRajput
works=true
component.ts
文件上设置不需要
[ngmodel]=true
如果更改ts文件或模板中的值,因为您使用的是双向绑定,则在两者上都进行反射。@Abhishek如果我需要选中某个条件的复选框,该怎么办。假设obj1={“property1”:“exist”}并选中复选框initially iff[checked]=“property=='exist',那么双向绑定[(ngModel)]@MohitRajput复选框将如何使用布尔值<代码>[选中]=“属性”设置属性为true。另一方面,如果exist设置为true
this.checkeValue=true
否则为false.true,则在ts文件中有check
property=='exist'
。我想勾选一个条件的复选框,比如如果某个表达式等于true,那么ngModel在这个场景中如何工作
<input [(ngModel)]="works" type="checkbox"/>
<input [checked]="works" type="checkbox" (change)="func($event)"/>
works: boolean;

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