代码之家  ›  专栏  ›  技术社区  ›  Hasan Zubairi

角度5复选框已选中数据状态

  •  0
  • Hasan Zubairi  · 技术社区  · 6 年前

    在我的应用程序中,数据来自具有嵌套数组的服务器,但没有用于检查复选框是否选中的字段,因此我使用foreach循环添加了该字段。即使该字段为真或假,也不起作用。我的代码如下。

    this.testservice.getQuestions()
              .subscribe(
              resultArray => {
              this.questions = resultArray;
                this.questions.forEach(element => {
                  element.Awnsers.forEach(elementA => {
                    elementA.isChekced = true;
                  });
                });
    

    输入的html代码是

    <div *ngFor='let q of questions'>
    <b>Question: </b>
      {{q.Question}}<br><br>
      <div *ngFor='let a of q.Awnsers'>
        <label>
          <input type="checkbox"
                 name="options"
                 value="{{a.awnsers}}"
                 (checked)="a.isChecked"
                 (change)="testoption($event, a.Awnser)" />
                 {{a.Awnser}}
      </label>
      </div>
     </div>
    

    事件属性isChecked对于所有元素都为true,但不进行检查。请帮忙。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Sajeetharan    6 年前

    使用angular时,它应写为[checked],表示数据绑定,如下所示进行更改,

      <input type="checkbox" name="options" value="{{a.awnsers}}" [checked]="a.isChecked"  (change)="testoption($event, a.Awnser)" />
    
        2
  •  2
  •   Prashant Pimpale Dila Gurung    6 年前

    如果角度版本是5,那么我会使用 [(ngModel)] 而不是 [checked] 属性,通过使用双向数据绑定,您将获得应答的当前状态,即 checked unchecked .

    <input type="checkbox" name="options" value="{{a.awnsers}}" [(ngModel)]="a.isChecked" (change)="testoption(i, a.Awnser)" />
    

    A Working StackBlitz

        3
  •  0
  •   junho    4 年前

    因为动画的缘故,我用了这种方式。

    <input #checkInput type="checkbox" />
    
    export class Component implements AfterViewInit {
      @ViewChild('checkInput', { static: false }) checkInput: ElementRef<HTMLElement>
      @Input() isOpen = false
      
      ngAfterViewInit() {
        if(this.isOpen) {
          this.checkInput.nativeElement.click()
        }
      }
    }