简体   繁体   English

如何从下拉菜单中为本地对象分配一个新值

[英]How to assign a local object a new value from a dropdown menu

I have an array of objects that all have a name property.我有一个对象数组,它们都有一个 name 属性。 In my drop-down, I display all of these objects using this name property.在我的下拉列表中,我使用这个 name 属性显示所有这些对象。 I want the user to be able to select a new name from the list, and assign the associated object to a variable named selectedGlobalClass .我希望用户能够从列表中选择一个新名称,并将关联的对象分配给名为selectedGlobalClass的变量。 How can I get this to happen?我怎样才能做到这一点?

Here is my html:这是我的 html:

<select (change)="changeClass(class)">
        <option *ngFor="let class of globalClasses" [selected]="class.GlobalClassID==selectedOption.FK_GlobalClassID">{{class.GlobalClassName}}</option>
    </select>

And TS:和 TS:

  changeClass(inputClass: GlobalClass): void {
this.selectedGlobalClass = inputClass;
  }

Also, when first opening the component, I would like to automatically select the item from the list in which the GlobalClassID is equal to the selectedOption property's FK_GlobalClassID .此外,当第一次打开组件时,我想从列表中自动选择GlobalClassID等于 selectedOption 属性的FK_GlobalClassID This is why I have the [selected]="class.GlobalClassID==selectedOption.FK_GlobalClassID"这就是为什么我有[selected]="class.GlobalClassID==selectedOption.FK_GlobalClassID"

Use Form Controls:使用表单控件:

add line to .ts file将行添加到 .ts 文件

className = new FormControl('');

This creates a new Form Control.这将创建一个新的表单控件。 (Angular Reactive Form). (角反应形式)。

use form control in html <select (change)="changeClass(className.value)" [formControl]="className"> <option value="class.GlobalClassName" *ngFor="let class of globalClasses" >{{class.GlobalClassName}}</option> </select>在html中使用表单控件<select (change)="changeClass(className.value)" [formControl]="className"> <option value="class.GlobalClassName" *ngFor="let class of globalClasses" >{{class.GlobalClassName}}</option> </select>

This creates a select that sets the value of the formControl in .ts file to class.GlobalClassName.这将创建一个选择,将 .ts 文件中的 formControl 的值设置为 class.GlobalClassName。

**Now: ** **现在: **

all you have to do now is in changeClass() is change the parameter to a string value and then use conditionals to set the variable equal to the specific object with the name from class.GlobalClassName.您现在要做的就是在 changeClass() 中将参数更改为字符串值,然后使用条件将变量设置为等于名称来自 class.GlobalClassName 的特定对象。

You just need to use angular reactive form你只需要使用角反应形式
Start by giving a formControlName to your selected field首先为您选择的字段提供一个 formControlName

in your html file在你的 html 文件中

<select (change)="changeClass(className.value)" formControlName="className">
<option [value]="class.GlobalClassName" *ngFor="let class of globalClasses" > 
{{class.GlobalClassName}}</option>
</select>

in ts file在 ts 文件中

    ngOnInit(){
    className = new FormControl('');
    }   

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

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