繁体   English   中英

如何使用Angular 5验证我的带复选框列表是否全部选中

[英]How to verify if my list with checkbox are all checked using Angular 5

我为每个项目创建了一个带有一个复选框的列表,并且我需要验证是否所有项目都被选中。

这是我的HTML:

<ul class="ingredient-list" >
   <li class="btn-list" *ngFor="let ingredient of recipe.ingredients">
        <label class="checky round">
          <input type="checkbox" checked>
          <span></span>
          <span>{{ ingredient }}</span>
        </label>
   </li>
</ul>

在您的组件ts文件中

import { FormArray, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

ingredientsForm;
constructor( private fb: FormBuilder) { }

ngOnInit() {
   //do what you need to get your recipe details first
   const ingredientFGs = recipe.ingredients.map(ingredient => this.fb.group(ingredient));

ingredientFGs.forEach(item => {
   item.addControl('isChecked', new FormControl());
   item.get('isChecked').setValue(false);
   item.get('isChecked').setValidators(Validators.requiredTrue);
})

this.ingredientsForm = this.fb.group({
   ingredients: this.fb.array(ingredientFGs);
});
}

并在您的html中

<form [formGroup]="ingredientsForm">
   <ul class="ingredient-list" formArrayName="ingredients">
      <li class="btn-list" *ngFor="let ingredient of ingredients.controls">
          <label class="checky round">
              <input type="checkbox" formControlName="isChecked">
              <span></span>
              <span>{{ ingredient.value() }}</span>
          </label>
      </li>
   </ul>
</form>

然后,如果检查了所有内容,则执行IngredientsForm.valid将返回true

当我不想导入其他模块只是为了解决这个问题时,我想到了另一个想法。

我在component.ts中创建了一个方法来验证复选框:

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

@Component({
  selector: 'app-recipes',
  templateUrl: './recipes.component.html',
  styleUrls: ['./recipes.component.css']
})
export class RecipesComponent  {

  @ViewChild('ingredientList') ingredientList: ElementRef;
  @ViewChild('preparationList') preparationList: ElementRef;



  isAllChecked(list: ElementRef): boolean{
    // take the inputs by tag and convert to array
    var inputs = [].slice.call(list.nativeElement.getElementsByTagName('input'));

    return !inputs.some(function(input){
        // verify if any item is not checked
        return input.ckecked == false;        
    });
  } 
}

我的HTML现在看起来像这样

<ul #ingredientList >
  <li  #item class="btn-list" *ngFor="let ingredient of recipe.ingredients">
    <label class="checky round">
      <input type="checkbox" >
      <span></span>
      <span>{{ ingredient }}</span>
    </label>
  </li>
</ul>

谢谢大家的帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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