简体   繁体   中英

How to validate checkbox coming from loop on submit without using reactive form - angular 8

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');  
 }
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM