简体   繁体   English

如何在没有输入元素或隐藏 UI 元素的情况下在 Angular 表单中分配值?

[英]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.下拉列表有一个ID作为值和Name作为显示值。

When I submit the form, I need both the values ID and Name to be in the form output当我提交表单时,我需要值IDName都在表单输出中

   <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提交表单后,我得到一个 JSON

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

When I submit the form, I also want the StateName to be in the form output.当我提交表单时,我还希望 StateName 出现在表单输出中。

How do I assign the StateName selected in the Dropdown, to a model property in the template-driven form?如何将下拉列表中选择的 StateName 分配给模板驱动表单中的模型属性?

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?是提交后在 Typescript 文件中执行此操作的唯一方法吗?

ViewChild comes handy in these situations: ViewChild在这些情况下派上用场:

HTML File: HTML文件:

<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:组件 TS 文件:

first declare an viewchild variable:首先声明一个viewchild变量:

@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;
    }

是的,根据给定的限制,您必须处理.ts文件中的表单提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM