angular - 我想使用 mat-select 的值作为键和输入字段的值作为角度反应形式的键的值
问题描述
这是我的用户界面
https://i.stack.imgur.com/NlBNA.png
我希望我的表单值像这样 {color :"red"} 其中 **mat-selects value is color** and **input field is red**. When I will change mat-select
的值是表示颜色也会改变的键。
假设我将 mat-select 的值从颜色更改为存储。
我的输出应该是 {storage:"red"}
假设我将输入字段的值从红色更改为“250Gb”。
我的输出应该是 {storage:"250Gb"}
如何以最好的方式解决这个问题。感谢您的帮助
我的 HTML:
<form [formGroup]="itemEntryForm" (submit)="onSaveitem()">
<div>
<mat-form-field appearance="outline" class="full-width-input">
<mat-label >Attribute :</mat-label>
<mat-select>
<mat-option *ngFor="let attribute of attributes" [value]="attribute.name">{{ attribute.name }}</mat-option>
</mat-select>
<mat-label><mat-icon>branding_watermark</mat-icon> <b>*Attribute </b> <i> label</i></mat-label>
</mat-form-field>
</div>
<div>
<mat-form-field class="full-width-input">
<mat-label >Attribute Value :</mat-label>
<input matInput name="item_attribute" placeholder="Color ,Storage" formControlName="item_attribute">
<mat-error *ngIf="itemEntryForm.get('item_attribute').invalid">Attribute</mat-error>
</mat-form-field>
</div>
<div>
</form>
我的 Ts 文件:
export class ItemEntryComponent implements OnInit {
itemEntryForm:FormGroup;
taxes = [{name:"tax"},{name:"tax2"}]
constructor(private _formbuilder:FormBuilder) { }
ngOnInit(): void {
this.itemEntryForm=this._formbuilder.group({
type : ['Goods'],
item_name : ['',Validators.required],
description : ['',Validators.required],
unit : ['pc',Validators.required],
tax : ['',],
manufacturer : ["",],
brand : ['',],
item_attribute : ['',],
item_attribute2: ['',],
image : ['',],
})
}
onSaveitem(){
console.log( this.itemEntryForm.value)
}
}
解决方案
尝试设置下拉列表的订阅以获取它的价值。可以作为表单控件的键。
setFormSubscription() {
this.itemEntryForm.controls.X.valueChanges.subscribe(new_X_Value => {
if (new_X_)Value && new_X_)Value.value) {
// new_X_)Value.value is because of considering it as dropdown.
if (!this.itemEntryForm.get(new_X_)Value.value)) { // if it's not already added.
this.itemEntryForm.addControl(new_X_)Value.value, new FormControl(''))
}
}
})
this.itemEntryForm.controls.Y.valueChanges.subscribe(new_Y_Value => {
if (this.itemEntryForm.get(NAME_OF_X_CONTROL)) {
this.itemEntryForm.get(NAME_OF_X_CONTROL).setValue(new_Y_Value);
// Here you need to make sure X Control exists
// To get Name of X Control, you can use list which is used for dropdown.
}
})
}
在表单创建之后调用 setFormSubscription函数。
更改值检查后,调用onSaveitem函数检查值。
推荐阅读
- google-analytics - Adwords 转换引发了谷歌分析与反应
- pytorch - 在 google-collaboratory 中使用 PyTorch 加载模型的问题
- django - 创建子窗体并同时修改父窗体,Django
- ios - 我应该使用 AVFoundation 或 CoreAudio 从文件或缓冲区中解码/转换音频吗?
- javascript - 如何根据窗口大小动态定位 div?
- c++ - 有人可以解释下面代码中标记为“Line1”的行吗?
- java - 如何使用 java io.fabric8 kubernetes-client 库覆盖默认 kubernetes 配置文件
- java - Swagger - @exampleproperty 可以动态更改以在 DTO 中显示新添加的字段
- java - 具有多个分区和多个侦听器的 Spring Kafka
- r - 从 R 中的列列表中引用数据框列