Home > OS >  Angular 13 Input Radio checked condition not working
Angular 13 Input Radio checked condition not working

Time:01-18

I save in localstorage selectedKitchenId, and checked or selectedKitchenId === kitchen.id, if true selected radio. Dont understand why not working checked conditions, i try strong tag display the same check everything works. Tell me what could be the reason

        <div class='row'>
          <div *ngFor="let kitchen of kitchenTypes" class='col-lg-3'>

            <div >
              <label  for="{{kitchen.id}}">
                <div class='kitchenTypeBg'>
                  <img src='{{kitchen.src}}' alt='' class='p-1 align-middle'>
                </div>
              </label>
              <input
                [checked]="selectedKitchenId === kitchen.id"
                formControlName="kitchenType"
                [value]='kitchen.id'
                 type="radio" id="{{kitchen.id}}"
              >
              <strong>{{selectedKitchenId === kitchen.id}}</strong>
            </div>
          </div>
        </div>

enter image description here

CodePudding user response:

It worked for me, Form Control pass value. How is it done here link

    // Get selected Kitchen id
    this.selectedKitchenId =
      this.persistenceService.get('selectedKitchenId') ?? null;


  initializeForm(): void {
    this.form = this.formBuilder.group({
      kitchenType: new FormControl(this.selectedKitchenId, Validators.required),
    });
  }

CodePudding user response:

     <form #f="ngForm" (ngSubmit)='goToNextStep(f.form)'>
        <div *ngIf="submitted && f.invalid">
           <span class='text-center'>Required form</span>
        </div>
        <div class='row'>
          <div *ngFor="let kitchen of kitchenTypes" class='col-lg-3'>

            <div >
              <label  [for]="kitchen.id">
                <div class='kitchenTypeBg'>
                  <img [src]='kitchen.src' alt='' 
                       class='p-1 align-middle'>
                </div>
              </label>
              <input
                name="kitchenType"
                [checked]="selectedKitchenId === kitchen.id"
                [value]='kitchen.id'
                 
                type="radio" 
                [id]="kitchen.id"
              >
              <strong>{{selectedKitchenId === kitchen.id}}</strong>
            </div>
          </div>
        </div>
        <div >
          <button type="submit" 
          >
            Tęsti
          </button>
          <button
            [routerLink]="['/']"
            class='btn btn-block mx-auto buttonBack'>
            <i ></i>
            Grižti
          </button>
        </div>
      </form>

This is how easy template-driven is

Fixed some best-practices for you

To get the values, just use like this on TS file:

goToNextStep(form) {
   const {kitchenType} = form.values
}
  •  Tags:  
  • Related