After adding [(ngModel)] to a radio button group, the default [checked] no longer works

前端 未结 3 637
渐次进展
渐次进展 2020-12-05 07:16

I\'m working on a small reusable Component which styles radio buttons and emits the selected values.

import { Component, OnInit, Input, Output, EventEmitter          


        
相关标签:
3条回答
  • 2020-12-05 07:36

    I think, you don't need this [checked]="choice === defaultChoice". Try this :

    <input type="radio"
           id="{{ groupName + choice }}"
           name="{{groupName}}"
           [value]="choice"
           [(ngModel)]="defaultChoice"
           (ngModelChange)="choose($event)" />
    

    When [value] = [(ngModel)] the radio is selected.

    0 讨论(0)
  • 2020-12-05 07:36

    export class ConfirmationmodalComponent implements OnInit {
      client_notification: any = false;
      candidate_notification: any = false;
      cancel_associated_session: any = false;
    
      constructor(
      ) {}
    
      ngOnInit(): void {
      }
    }
    <div class="form-check form-check-inline">
      <input
        class="form-check-input"
        type="radio"
        id="inlineRadio1"
        name="cancel_associated_session"
        [(ngModel)]="cancel_associated_session"
        [value]="true"
      />
      <label class="form-check-label" for="inlineRadio1">
        Yes
      </label>
    </div>
    <div class="form-check form-check-inline">
      <input
        class="form-check-input"
        type="radio"
        id="inlineRadio2"
        name="cancel_associated_session"
        [(ngModel)]="cancel_associated_session"
        [value]="false"
      />
      <label class="form-check-label" for="inlineRadio2">
        No
      </label>
    </div>

    0 讨论(0)
  • 2020-12-05 07:38

    I was able to emit the value and retain the default styling with minimal changes by altering the input's template to:

    <input type="radio"
           id="{{ groupName + choice }}"
           name="{{groupName}}"
           value="{{ choice }}"
           [checked]="choice === defaultChoice"
           (click)="choose($event['target']['value'])" />
    

    ...which I find kind of hacky. It also doesn't explain why adding data/property binding broke it, so I'm open to more suggestions.

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