Home > Software engineering >  onChange function only working on second click
onChange function only working on second click

Time:09-30

I have a form that I need the additional description input to show when 'other' is selected from the dropdown, however with the current function this only works on the second selection.

It currently works if a section is made, then cleared and then 'Other' is selected. I need this to fire and display the other box on the first click if required by the user.

HTML --

           <form  [formGroup]="unableToScanForm" *ngIf="!loading" (ngSubmit)="onSubmit()">
            <div >
              <div >
                <div >
                  <label  for="reasonType"><strong>Reason*</strong></label>
                  <div >
                    <ng-select id="reasonType" name="reasonType"
                               placeholder="Select a reason..."
                               labelForId="reasonType"
                               formControlName="reasonType"
                               [multiple]="false"
                               [hideSelected]="true"
                               [closeOnSelect]="true"
                               [items]="reasonType"
                               [searchable]="false"
                               bindLabel="type"
                               bindValue="type"
                               [ngClass]="{ 'is-invalid': submitted && f.reasonType.errors }">
                    </ng-select>
                    <div *ngIf="submitted && f.reasonType.errors" >
                      Please select a reason.
                    </div>
                  </div>
                </div>

                <div  *ngIf="showAdditionalInfo">
                  <label  for="reasonDescription"><strong>Additional Information*</strong></label>
                  <div >
                  <textarea
                            rows="3"
                            
                            id="reasonDescription"
                            formControlName="reasonDescription"
                            [ngClass]="{ 'is-invalid': submitted && f.reasonDescription.errors }">
                  </textarea>
                    <div *ngIf="submitted && f.reasonDescription.errors" >
                      Please detail a description of the reason.
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </form>

TS --

  reasonSelection(): void {
    this.unableToScanForm.valueChanges.subscribe(value => {
      if (value.reasonType === 'Other') {
        this.showAdditionalInfo = true;
      }
    });
  }

CodePudding user response:

Suppose you have to start listen changes with the first form value:

reasonSelection(): void {
    this.unableToScanForm.valueChanges
      .pipe(startWith(this.unableToScanForm.value))
      .subscribe(...);
  }
  • Related