Angular 5 checkbox checked status from data

Issue

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.

Solution

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 i.e checked or unchecked.

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

A Working StackBlitz

Answered By – Prashant Pimpale

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.