Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 如何根据angular 7中的某些值在默认情况下获取特定复选框_Html_Css_Typescript_Angular7 - Fatal编程技术网

Html 如何根据angular 7中的某些值在默认情况下获取特定复选框

Html 如何根据angular 7中的某些值在默认情况下获取特定复选框,html,css,typescript,angular7,Html,Css,Typescript,Angular7,我有一个复选框和选择框,其值来自循环,但这里我需要根据对象数组默认选中一些复选框。这里的复选框和选择框值来自usersg和usersr变量。但是默认选中和选择的值应该来自ngOnInit()中的变量usersg_checked和usersr_selected. 下面是代码 home.component.html 在组件中添加isChecked()方法,以检查是否必须选中复选框 组件: isChecked(id) { return this.usersg_checked.some(item =

我有一个复选框和选择框,其值来自循环,但这里我需要根据对象数组默认选中一些复选框。这里的复选框和选择框值来自usersg和usersr变量。但是默认选中和选择的值应该来自ngOnInit()中的变量usersg_checked和usersr_selected. 下面是代码

home.component.html 在组件中添加
isChecked()
方法,以检查是否必须选中复选框

组件:

isChecked(id) {
  return this.usersg_checked.some(item => item.id === id);
}
<p *ngFor="let group of usersg">
  <input type="checkbox" [checked]="isChecked(group.id)" value="{{group.id}}" />{{group.name}}
</p>
<p><select [(ngModel)]="usersr_selected.id">
   <option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option> 
</select></p>
模板:

isChecked(id) {
  return this.usersg_checked.some(item => item.id === id);
}
<p *ngFor="let group of usersg">
  <input type="checkbox" [checked]="isChecked(group.id)" value="{{group.id}}" />{{group.name}}
</p>
<p><select [(ngModel)]="usersr_selected.id">
   <option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option> 
</select></p>
组件:

isChecked(id) {
  return this.usersg_checked.some(item => item.id === id);
}
<p *ngFor="let group of usersg">
  <input type="checkbox" [checked]="isChecked(group.id)" value="{{group.id}}" />{{group.name}}
</p>
<p><select [(ngModel)]="usersr_selected.id">
   <option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option> 
</select></p>
并将
usersr\u selected
更改为一个对象

ngOnInit() {
  this.usersr_selected = {"id":1,"name":"test1"};
}  
如果所选的
usersr\u
是一个数组,请将数组的第一个元素用作
NgModel

ngOnInit() {
  this.usersr_selected = this.usersr_selected[0];
}  

谢谢你的回答,两个都很好,但是对于select{“id”:1,“name”:“test1”};需要是像[{“id”:1,“name”:“test1”}]这样的对象数组;在我的例子中,它来自我的项目中的API,我无法更改它。@UIAPPDEVELOPER-查看我编辑的答案,如果有任何问题,请告诉我。在我的项目中,它的显示无法读取某些属性undefined@UIAPPDEVELOPER-这意味着您在呈现视图时没有可用的
this.usersg\u检查数据。添加
*ngIf

。如果您还有任何错误,请告诉我。