Getting value from checked box in angular 2 typescript

前端 未结 6 750
再見小時候
再見小時候 2021-02-04 03:58

I am using Angular 2 Typescript. I am facing a problem wherein I need to submit a form which contains check boxes. I need values that are in the attributes of checkboxes. The ch

相关标签:
6条回答
  • 2021-02-04 04:03

    I use this for the checkboxes: ng2-material checkbox

    And you could do this in your component:

    <md-checkbox [checked]="exists(label.Id)" (click)="toggle(label.Id)"></md-checkbox>
    
      selected = [];
      @Output() selectedChange:EventEmitter<any> = new EventEmitter();
    
      toggle(id) {
        var index = this.selected.indexOf(id);
        if (index === -1) this.selected.push(id);
        else this.selected.splice(index, 1);
        this.selectedChange.emit(this.selected);
      }
    
      exists(id) {
        return this.selected.indexOf(id) > -1;
      }
    
    0 讨论(0)
  • 2021-02-04 04:04

    I think you want to know checkbox that checked or not which you can easily get in the form of boolean value by specifying ng-model attribute for input tag attribute.

    <md-checkbox ng-model="ctrl.someBooleanValue"></md-checkbox>
    

    for more info check angular material md-checkbox and angular material md-checkbox demo

    0 讨论(0)
  • 2021-02-04 04:12

    Input

    <input type="checkbox" (change)="selectionChange($event.srcElement, dataItem)">
    

    Change Event

    selectionChange(input: HTMLInputElement) {
        input.checked === true
          ? doSomethingIfTrue()
          : doSomethingIfFalse();
    }
    
    0 讨论(0)
  • 2021-02-04 04:16

    I think this should work (not tested)

    <div class="checkbox" *ngFor="let label of labelList">
      <div class="col-sm-4">
        <label>
          <input type="checkbox" value="{{label.Id}}" (change)="checkboxes[$event.target.getAttribute('value')]=$event.target.checked">
            {{ label.Name }}</label>
      </div>   
    </div>
    

    and store the values of changed checkboxes in checkboxes in your component.

    0 讨论(0)
  • 2021-02-04 04:20

    You have to specify name attribute for checkbox to able to track it on backend.

    0 讨论(0)
  • 2021-02-04 04:27
    enter code here
    

    submitForm(form:NgForm){
    console.log(form.value);
    }
    <div class="checkbox" *ngFor="#label of labelList">
           <div class="col-sm-4">
                <label><input type="checkbox" name='label{{label.Id}}'  value="{{label.Id}}">{{ label.Name }} </label>
           </div>   
     </div>

    Use name attribute including label.id,so you will get all value in array form.

    GUESS THIS WILL HELP.

    0 讨论(0)
提交回复
热议问题