Search code examples
htmlangulartypescriptangular-reactive-forms

Show checkbox checked in reactive form load in angular


I want to show my checkbox checked when my form loads. In my Html page:-

<div>
    Is Active
</div>
<div class="form-group">
    <input type="checkbox" formControlName="IsActive" [ngModel]="isactivechk">
</div>

Code In my .ts page

export class UserregistrationComponent {
isactivechk:boolean=true;
}

This is a child control using it in a parent controller. I want to check the checkbox on Parent page load


Solution

  • If your checkbox is part of a child component and you want to pre-check it from the parent component, you'll need to make sure you're passing the initial value correctly and managing the form control from the parent component. Here's how you can approach this Let's say you have a parent component (parent.component.ts) and a child component (child.component.ts). In the child component's template (child.component.html), you'll define the checkbox like this.

    <!-- child.component.html -->
    <label>
      <input type="checkbox" [formControl]="myCheckboxControl"> My Checkbox
    </label>
    

    In the child component's TypeScript file (child.component.ts), define an Input property to receive the form control from the parent.

    import { Component, Input } from '@angular/core';
    import { FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
    })
    export class ChildComponent {
      @Input() myCheckboxControl: FormControl;
    }
    

    In the parent component's template (parent.component.html), use the child component and pass the form control to it.

    <!-- parent.component.html -->
    <app-child [myCheckboxControl]="myForm.get('myCheckbox')"></app-child>
    

    In the parent component's TypeScript file (parent.component.ts), you'll define the form and its initial value:

    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';
    
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
    })
    export class ParentComponent implements OnInit {
      myForm: FormGroup;
    
      constructor(private formBuilder: FormBuilder) {}
    
      ngOnInit() {
        this.myForm = this.formBuilder.group({
          myCheckbox: [true] // Set the initial value here (true for checked, false for unchecked)
        });
      }
    }
    

    By passing the form control to the child component as an @Input() property, you ensure that the form control is shared between the parent and the child components. This way, when the form initializes in the parent component, the checkbox in the child component should be pre-checked accordingly.