簡體   English   中英

如何在不使用反應形式的情況下驗證來自循環提交的復選框 - angular 8

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

我有幾個來自循環的復選框,當沒有選中任何復選框並單擊提交按鈕時,應顯示錯誤消息,一旦選中任何復選框且驗證成功,將顯示控制台值。不使用反應式表單。 這是下面的代碼https://stackblitz.com/edit/angular-grb6yw?file=src%2Fapp%2Fapp.component.html

應用程序組件.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');  
 }
}

組件.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;
    }
  }
}

組件.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM