简体   繁体   中英

Angular 13 Input Radio checked condition not working

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 class="form-check form-check-inline">
              <label class="form-check-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'
                class="form-check-input" type="radio" id="{{kitchen.id}}"
              >
              <strong>{{selectedKitchenId === kitchen.id}}</strong>
            </div>
          </div>
        </div>

在此处输入图像描述

 <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 class="form-check form-check-inline"> <label class="form-check-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' class="form-check-input" type="radio" [id]="kitchen.id" > <strong>{{selectedKitchenId === kitchen.id}}</strong> </div> </div> </div> <div class="d-grid"> <button type="submit" class="btn-block btn btn-outline-light buttonNext mx-auto mt-4 w-50"> Tęsti </button> <button [routerLink]="['/']" class='btn btn-block mx-auto buttonBack'> <i class="bi bi-arrow-left"></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
}

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),
    });
  }

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