Default value on radio input and input at the same time

Viewed 73

I have an array of objects that i need to edit. The array is like:

{
  answers: [ { answer: 'answer 1', isValid: true }, { answer: 'answer 2, isValid: false } ]
}

I do ngFor for create a inputs as long as answers.length

<div class="form-group" *ngFor="let answer of editItem.answers">
    <div class="input-group">
         <div class="input-group-prepend">
               <div class="input-group-text">
                    <input type="radio" [(ngModel)]="answer.isValid" [value]="answer.isValid">
               </div>
         </div>
         <input type="text" class="form-control"  [(ngModel)]="answer.answer">
    </div>
</div>

I need default value on both, and only 1 radioinput checked.

How can i do that?

1 Answers

Have a look at this Stackblitz example for Radio Inputs to fix your issue.

E.g.:

template:

<h2>{{radioTitle}}</h2>
<label *ngFor="let radiobutton of radioItems">
  <input type="radio" name="options" (click)="model.option = radiobutton"
  [checked]="radiobutton === model.option">{{radiobutton}}
</label>
<p>
  <button (click)="model.option = 'option1'">
    Set option #1
  </button>
</p>
<p>
  Selected option: {{model.option}}
</p>

app.component

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  radioTitle: string;
  radioItems: Array<string>;
  model   = {option: 'option3'};

  constructor() {
    this.radioTitle = 'Radio Button in Angular';
    this.radioItems = ['option1', 'option2', 'option3'];
  }
}
Related