Search code examples
angularangular-uiangular-ui-select

How to assign values in an Angular form without an input element or hiding the UI element?


I am working on this template-driven form, where I have a dropdown.

The dropdown has an ID as value and Name as the display value.

When I submit the form, I need both the values ID and Name to be in the form output

   <mat-form-field>
            <mat-label>State</mat-label>
            <mat-select [(ngModel)]="data.stateCode" name="StateCode" #yddfyty>
              <mat-option *ngFor="let state of stateOptions" [value]="state.ID">
                {{state.name}}
              </mat-option>
            </mat-select>
   </mat-form-field>

After submitting the form, I get a JSON

{
  StateCode: "Option I select in the Dropdown"
}

When I submit the form, I also want the StateName to be in the form output.

How do I assign the StateName selected in the Dropdown, to a model property in the template-driven form?

I can think of a way where we can use an element and hide the element, Is there any other way?

Is the only way to do it in the Typescript file after submitting?


Solution

  • ViewChild comes handy in these situations:

    HTML File:

    <mat-form-field>
                <mat-label>State</mat-label>
                <mat-select  name="StateCode" #ElementRef>
                  <mat-option *ngFor="let state of stateOptions" [value]="state.ID">
                    {{state.name}}
                  </mat-option>
                </mat-select>
       </mat-form-field>
    

    Component TS File:

    first declare an viewchild variable:

    @ViewChild('ElementRef') stateElement: any;
    

    and later on you can use this variable when you submit the form:

        OnSubmit(){
         let selectedStateCode = this.stateElement.nativeElement.value//selected dropdown value
         let selectedStateText = this.stateElement.nativeElement.textContent //selected dropdown text
         //rest of your submit code;
        }