简体   繁体   中英

Angular 5 checkbox checked status from data

In my app data is coming from the server with nested arrays but there is no field for the check if the checkbox is checked or not so I added that field with foreach loop. This field has no effect even if it is true or false. My code is as follows.

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

the html code for input is

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

Event the property isChecked is true for all the elements but they are not coming checked. Please help.

With angular it should be written as [checked] which indicates the data binding, change it as follows,

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

If the Angular version is 5 then I would use [(ngModel)] instead of [checked] attribute, by using two-way data binding, you will get the current status of answer ie checked or unchecked .

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

A Working StackBlitz

Beacause of animation, I used this way.

<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()
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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