簡體   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