prosource

각도 2: 여러 체크박스의 값을 가져옵니다.

probook 2023. 2. 22. 22:20
반응형

각도 2: 여러 체크박스의 값을 가져옵니다.

문제는 매우 간단합니다.다음과 같은 확인란 목록이 있습니다.

<div class="form-group">
    <label for="options">Options :</label>
    <label *ngFor="#option of options" class="form-control">
        <input type="checkbox" name="options" value="option" /> {{option}}
    </label>
</div>

그리고 다음과 같은 선택된 옵션 배열을 보내드리겠습니다.[option1, option5, option8]옵션 1, 5, 8이 선택되어 있는 경우.이 어레이는 HTTP PUT 요청을 통해 전송하고 싶은 JSON의 일부입니다.

도와주셔서 감사합니다!

여기 간단한 사용 방법이 있습니다.ngModel(최종 각도 2)

<!-- my.component.html -->

<div class="form-group">
    <label for="options">Options:</label>
    <div *ngFor="let option of options">
        <label>
            <input type="checkbox"
                   name="options"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"/>
            {{option.name}}
        </label>
    </div>
</div>

// my.component.ts

@Component({ moduleId:module.id, templateUrl:'my.component.html'})

export class MyComponent {
  options = [
    {name:'OptionA', value:'1', checked:true},
    {name:'OptionB', value:'2', checked:false},
    {name:'OptionC', value:'3', checked:true}
  ]

  get selectedOptions() { // right now: ['1','3']
    return this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value)
  }
}

난 건터 덕분에 해결책을 찾아야 해!누구에게나 도움이 될 수 있는 경우는, 이하와 같이 해 주세요.

<div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="#option of options; #i = index">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option}}"
                           [checked]="options.indexOf(option) >= 0"
                           (change)="updateCheckedOptions(option, $event)"/>
                    {{option}}
                </label>
            </div>
        </div>

사용하고 있는 3개의 오브젝트는 다음과 같습니다.

options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
        OptionA: false,
        OptionB: false,
        OptionC: false,
};
optionsChecked = [];

그리고 3가지 유용한 방법이 있습니다.

1. 개시하다optionsMap:

initOptionsMap() {
    for (var x = 0; x<this.order.options.length; x++) {
        this.optionsMap[this.options[x]] = true;
    }
}

2. 갱신하는 방법optionsMap:

updateCheckedOptions(option, event) {
   this.optionsMap[option] = event.target.checked;
}

3. 변환하다optionsMap안으로optionsChecked저장하다optionsPOST 요구를 송신하기 전에, 다음을 실시합니다.

updateOptions() {
    for(var x in this.optionsMap) {
        if(this.optionsMap[x]) {
            this.optionsChecked.push(x);
        }
    }
    this.options = this.optionsChecked;
    this.optionsChecked = [];
}

다음과 같은 목록을 만듭니다.

this.xyzlist = [
  {
    id: 1,
    value: 'option1'
  },
  {
    id: 2,
    value: 'option2'
  }
];

HTML :-

<div class="checkbox" *ngFor="let list of xyzlist">
            <label>
              <input formControlName="interestSectors" type="checkbox" value="{{list.id}}" (change)="onCheckboxChange(list,$event)">{{list.value}}</label>
          </div>

컴포넌트 ts:-에 있습니다.

onCheckboxChange(option, event) {
     if(event.target.checked) {
       this.checkedList.push(option.id);
     } else {
     for(var i=0 ; i < this.xyzlist.length; i++) {
       if(this.checkedList[i] == option.id) {
         this.checkedList.splice(i,1);
      }
    }
  }
  console.log(this.checkedList);
}
<input type="checkbox" name="options" value="option" (change)="updateChecked(option, $event)" /> 

export class MyComponent {
  checked: boolean[] = [];
  updateChecked(option, event) {
    this.checked[option]=event; // or `event.target.value` not sure what this event looks like
  }
}

저도 같은 문제에 부딪혀서 더 마음에 드는 답변이 나왔습니다(당신도 마찬가지일지도 모릅니다.각 확인란을 배열 인덱스로 제한했습니다.

처음에 오브젝트를 다음과 같이 정의했습니다.

SelectionStatusOfMutants: any = {};

그러면 체크박스는 다음과 같습니다.

<input *ngFor="let Mutant of Mutants" type="checkbox"
[(ngModel)]="SelectionStatusOfMutants[Mutant.Id]" [value]="Mutant.Id" />

아시다시피 JS의 객체는 임의의 인덱스를 가진 배열입니다.따라서 결과는 매우 단순합니다.

선택한 항목을 다음과 같이 세십시오.

let count = 0;
    Object.keys(SelectionStatusOfMutants).forEach((item, index) => {
        if (SelectionStatusOfMutants[item])
            count++;
    });

그리고 다음과 같이 선택한 항목을 가져옵니다.

let selecteds = Object.keys(SelectionStatusOfMutants).filter((item, index) => {
        return SelectionStatusOfMutants[item];
    });

봤지?매우 단순하고 매우 아름답습니다.TG.

다음은 지도, '확인된' 속성 및 Form Control이 없는 솔루션입니다.

app.component.component:

<div *ngFor="let item of options">
  <input type="checkbox" 
  (change)="onChange($event.target.checked, item)"
  [checked]="checked(item)"
>
  {{item}}
</div>

app.component.ts:

  options = ["1", "2", "3", "4", "5"]
  selected = ["1", "2", "5"]

  // check if the item are selected
  checked(item){
    if(this.selected.indexOf(item) != -1){
      return true;
    }
  }

  // when checkbox change, add/remove the item from the array
  onChange(checked, item){
    if(checked){
    this.selected.push(item);
    } else {
      this.selected.splice(this.selected.indexOf(item), 1)
    }
  }

데모

저는 이것이 같은 문제를 가진 사람에게 도움이 되기를 바랍니다.

템플릿

<form [formGroup] = "myForm" (ngSubmit) = "confirmFlights(myForm.value)">
  <ng-template ngFor [ngForOf]="flightList" let-flight let-i="index" >
     <input type="checkbox" [value]="flight.id" formControlName="flightid"
         (change)="flightids[i]=[$event.target.checked,$event.target.getAttribute('value')]" >
  </ng-template>
</form>

컴포넌트.ts 를 참조해 주세요.

flightids 배열에는 [[ true , 'id _ 1 ] , [ false , 'id _ 2 ] , [ true , id _ 3 ]... 같은 다른 배열이 있습니다.여기서 true는 사용자가 체크하고 false는 사용자가 체크하고 체크하지 않은 것을 의미합니다.사용자가 체크하지 않은 항목은 어레이에 삽입되지 않습니다.

flightids = []; 
confirmFlights(value){  
    //console.log(this.flightids);

    let confirmList = [];
    this.flightids.forEach(id => {
      if(id[0]) // here, true means that user checked the item 
        confirmList.push(this.flightList.find(x => x.id === id[1]));
    });
    //console.log(confirmList);

}

Typescript를 사용하여 각도 2+에서 9까지

소스 링크

여기에 이미지 설명 입력

개체를 사용하여 여러 개의 체크박스를 바인딩할 수 있습니다.

  checkboxesDataList = [
    {
      id: 'C001',
      label: 'Photography',
      isChecked: true
    },
    {
      id: 'C002',
      label: 'Writing',
      isChecked: true
    },
    {
      id: 'C003',
      label: 'Painting',
      isChecked: true
    },
    {
      id: 'C004',
      label: 'Knitting',
      isChecked: false
    },
    {
      id: 'C004',
      label: 'Dancing',
      isChecked: false
    },
    {
      id: 'C005',
      label: 'Gardening',
      isChecked: true
    },
    {
      id: 'C006',
      label: 'Drawing',
      isChecked: true
    },
    {
      id: 'C007',
      label: 'Gyming',
      isChecked: false
    },
    {
      id: 'C008',
      label: 'Cooking',
      isChecked: true
    },
    {
      id: 'C009',
      label: 'Scrapbooking',
      isChecked: false
    },
    {
      id: 'C010',
      label: 'Origami',
      isChecked: false
    }
  ]

HTML 템플릿 사용

  <ul class="checkbox-items">
    <li *ngFor="let item of checkboxesDataList">
      <input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
    </li>
  </ul>

선택한 확인란을 가져오려면 클래스에 다음 메서드를 추가하십시오.

  // Selected item
  fetchSelectedItems() {
    this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
      return value.isChecked
    });
  }

  // IDs of selected item
  fetchCheckedIDs() {
    this.checkedIDs = []
    this.checkboxesDataList.forEach((value, index) => {
      if (value.isChecked) {
        this.checkedIDs.push(value.id);
      }
    });
  }
  1. 오브젝트 XYZ를 사용하고 있는 분들을 위해 조금 간략하게 설명했습니다.컴포넌트.html

    <div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="let option of xyzlist">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option.Id}}"
    
                           (change)="onClicked(option, $event)"/>
                    {{option.Id}}-- {{option.checked}}
                </label>
            </div>
            <button type="submit">Submit</button>
        </div> 
    

    ** XYZ.Component.ts**.

  2. 목록을 만듭니다.xyzlist

  3. 값을 할당합니다. 이 목록의 Java에서 값을 전달합니다.
  4. 값은 Int-Id, boolean-checked(Can Pass in Component.ts)입니다.
  5. Componentenet.ts의 가치를 확인해보겠습니다.

    xyzlist;//Just created a list
    onClicked(option, event) {
        console.log("event  " + this.xyzlist.length);
        console.log("event  checked" + event.target.checked);
        console.log("event  checked" + event.target.value);
        for (var i = 0; i < this.xyzlist.length; i++) {
            console.log("test --- " + this.xyzlist[i].Id;
            if (this.xyzlist[i].Id == event.target.value) {
                this.xyzlist[i].checked = event.target.checked;
            }
            console.log("after update of checkbox" + this.xyzlist[i].checked);
    
        }
    

저는 이 문제에 직면했고, 작업 공간을 깨끗하게 유지하기 위해 가능한 한 적은 변수로 모든 것을 작동시키기로 결정했습니다.다음은 내 코드의 예입니다.

<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />

변경에 대해 호출된 메서드는 모델의 값을 푸시하거나 제거하는 것입니다.

public changeModel(ev, list, val) {
  if (ev.target.checked) {
    list.push(val);
  } else {
    let i = list.indexOf(val);
    list.splice(i, 1);
  }
}

위의 @ccwasden 솔루션은 약간의 변경으로 사용할 수 있습니다.각 체크박스는 고유한 이름을 가져야 합니다.그렇지 않으면 바인딩이 동작하지 않습니다.

<div class="form-group">
    <label for="options">Options:</label>
    <div *ngFor="let option of options; let i = index">
        <label>
            <input type="checkbox"
                   name="options_{{i}}"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"/>
            {{option.name}}
        </label>
    </div>
</div>

// my.component.ts

@Component({ moduleId:module.id, templateUrl:'my.component.html'})

export class MyComponent {
  options = [
    {name:'OptionA', value:'1', checked:true},
    {name:'OptionB', value:'2', checked:false},
    {name:'OptionC', value:'3', checked:true}
  ]

  get selectedOptions() { // right now: ['1','3']
    return this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value)
  }
}

또한 메인 모듈에서 Forms Module을 Import하도록 sur를 만듭니다.

import { FormsModule } from '@angular/forms';


imports: [
    FormsModule
  ],

비슷한 문제를 푸는 데 오랜 시간이 걸렸기 때문에 제 경험을 공유하기 위해 이렇게 답합니다.문제는 특정 이벤트가 트리거된 후에 많은 확인란 값을 얻는 것과 같았습니다.저는 많은 해결책을 시도했지만, 저는 ViewChildren을 사용하는 것이 가장 섹시합니다.

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

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components: QueryList<any>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

검색처: https://stackoverflow.com/a/40165639/4775727

레퍼런스를 위한 다른 잠재적인 솔루션에는 비슷한 토픽이 많이 있지만, 이 솔루션을 목적으로 하는 것은 없습니다.:

언급URL : https://stackoverflow.com/questions/34997128/angular-2-get-values-of-multiple-checked-checkboxes

반응형