【问题标题】:How to get check particular checkboxes by default based on some values in angular 7如何根据角度 7 中的某些值默认检查特定复选框
【发布时间】:2020-02-14 16:48:21
【问题描述】:

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

home.component.html

<p *ngFor="let group of usersg"><input type="checkbox" checked="checked.id" value="{{group.id}}" />{{group.name}}</p>

<p><select><option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option></select></p>

home.component.html

import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

    submitted = false;
    usersg_checked:any;
    usersr_selected:any;

 constructor(private formBuilder: FormBuilder) {


     }
public usersg = [{"id":1,"name":"test1"},{"id":2,"name":"test2"},{"id":3,"name":"test3"},{"id":4,"name":"test4"}];

public usersr = [{"id":1,"name":"test1"},{"id":2,"name":"test2"}];


  ngOnInit() {
this.usersg_checked = [{"id":1,"name":"test1"},{"id":2,"name":"test2"}];

this.usersr_selected = [{"id":1,"name":"test1"}];


  }


}

【问题讨论】:

    标签: html css typescript angular7


    【解决方案1】:

    在组件中添加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>
    

    对于&lt;select&gt; 元素最好使用[(ngModel)]

    模板:

    <p><select [(ngModel)]="usersr_selected.id">
       <option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option> 
    </select></p>
    

    组件:

    并将usersr_selected 更改为一个对象。

    ngOnInit() {
      this.usersr_selected = {"id":1,"name":"test1"};
    }  
    

    如果usersr_selected 是一个数组,则使用数组的第一个元素作为NgModel

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

    【讨论】:

    • 感谢您的回答,两者都工作正常,但对于 select {"id":1,"name":"test1"};需要是对象数组,例如 [{"id":1,"name":"test1"}];就我而言,这是来自我项目中的 API,我无法更改它。
    • @UIAPPDEVELOPER - 查看我编辑的答案,如果您有任何问题,请告诉我。
    • 在我的项目中它的显示无法读取一些未定义的属性
    • @UIAPPDEVELOPER - 这意味着您在呈现视图时没有可用的this.usersg_checked 数据。添加*ngIf 喜欢&lt;ng-container *ngIf="usersg_checked"&gt; &lt;p *ngFor="let group of usersg"&gt; ... &lt;/p&gt;&lt;/ng-container&gt;。如果您仍然有任何错误,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 2019-03-13
    • 2014-06-06
    相关资源
    最近更新 更多