0
votes

I have few checkbox coming from loop,When none of the checkbox is selected and click submit button,error message should be displayed,once any checkbox selected and validation successful only, console value to be display.Without using reactive form. Here is the code below https://stackblitz.com/edit/angular-grb6yw?file=src%2Fapp%2Fapp.component.html

app.component.html

<div>
<p>Form 3</p>
<div *ngFor="let grpdata of statusdata">
<input type="checkbox"  value="{{grpdata.groupid}}" class="form-control">{{grpdata.groupname}}<br>
</div>
<div>
                        <div [hidden]="errormessage">At least one should be checked</div>
                    </div>
<button type="submit" (click)="editSelectedVal()">Click here</button>

</div>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  statusdata :any;
  errormessage:boolean = true;
ngOnInit() {
this.statusdata = [{"groupid":1,"groupname":"project1"},{"groupid":2,"groupname":"project2"},{"groupid":3,"groupname":"project3"}];
}

editSelectedVal(){
console.log('submitted edit');  
 }
}
1
is it possible to use template driven forms ? (ngModle)AbolfazlR
The right way to do this is Form Arraycaden311
@caden311 - he said I do not want to use reactive form ...AbolfazlR
@AbolfazlR I know but he's doing it the hard way if he doesn't. Learn them, they are there for a reason.caden311

1 Answers

0
votes

component.ts

import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChildren('data') checkboxes !: QueryList<ElementRef>;
  name = 'Angular';
  statusdata :any;
  errormessage:boolean = true;

  ngOnInit() {
    this.statusdata = [{"groupid":1,"groupname":"project1"},{"groupid":2,"groupname":"project2"},{"groupid":3,"groupname":"project3"}];
  }

  editSelectedVal(){
    const checks: boolean[] = this.checkboxes.map(
      checkbox => { return checkbox.nativeElement.checked; }
    );
    console.log(checks);
    if(checks.indexOf(true) === -1) {
      console.log('not passed');
      this.errormessage = false;
    } else {
      console.log('passed');
      this.errormessage = true;
    }
  }
}

component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happenss :)
</p>
<div>
  <p>Form 3</p>
  <div *ngFor="let grpdata of statusdata">

    <input #data type="checkbox"  value="{{grpdata.groupid}}" class="form-control">{{grpdata.groupname}}
    <br />

  </div>
  <div>
    <div [hidden]="errormessage">At least one should be checked</div>
  </div>
  <button type="submit" (click)="editSelectedVal()">Click here</button>
</div>