Search code examples
htmlcsstypescriptangular7

How to get check particular checkboxes by default based on some values in angular 7


I have a checkboxes and selectbox whose values are coming from loop,but here I need to get some checkboxes checked by default based on an array of object.Here checkbox and selectbox value is coming from usersg and usersr variable.But the checked and selected by default should be from variable usersg_checked and usersr_selected inside ngOnInit(). Here is the code below

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"}];


  }


}

Solution

  • Add isChecked() method in component to check if a checkbox must be selected.

    Component:

    isChecked(id) {
      return this.usersg_checked.some(item => item.id === id);
    }
    

    Template:

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

    For <select> elements better to use [(ngModel)].

    Template:

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

    Component:

    And change usersr_selected to an object.

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

    If usersr_selected is an array, use the first element of the array as NgModel.

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