将要从mat-select表单中绑定的选定值传递给提交按钮功能
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将要从mat-select表单中绑定的选定值传递给提交按钮功能相关的知识,希望对你有一定的参考价值。
我正在尝试将用户选择的工具值中的instrumentName字段传递给Submit按钮中的函数。 instrumentName值显示正确,但似乎从未在提交时保存。所有其他输入值都可以保存。我该如何解决?
html:
<form [formGroup]="createForm" class="create-form">
<mat-form-field class="field-full-width">
<mat-label>Instrument</mat-label>
<mat-select matInput formControlName="Machine_ID" #Machine_ID>
<mat-option *ngFor="let instrument of instruments" [value]="instrument.instrumentName">
instrument.instrumentName
</mat-option>
</mat-select>
</mat-form-field>
<button type="submit" (click)="addSample( Machine_ID.value)"
[disabled]="createForm.pristine || createForm.invalid" mat-raised-button color="primary">Save</button>
</form>
TS代码:
import Component, OnInit from '@angular/core';
import FormGroup, FormBuilder, Validators from '@angular/forms';
import Router from '@angular/router';
import FileService from '../../file.service';
import Instrument from '../../instrument.model';
@Component(
selector: 'app-add-new-sample',
templateUrl: './add-new-sample.component.html',
styleUrls: ['./add-new-sample.component.css']
)
export class AddNewSampleComponent implements OnInit
createForm: FormGroup;
instruments: Instrument[];
constructor(private fileService: FileService, private fb: FormBuilder, private router: Router)
this.createForm = this.fb.group(
//other inputs...
Machine_ID: '',
);
addSample(/*other inputs*/, Machine_ID)
this.fileService.addSample(/*other inputs*/, Machine_ID).subscribe(() =>
this.router.navigate(['/instruments']);
);
fetchInstruments()
this.fileService.getInstruments()
.subscribe((data: Instrument[])=>
this.instruments = data;
)
ngOnInit()
this.fetchInstruments();
答案
您不需要通过模板传递Machine_ID参考。您可以像这样调用formGroup并获取Machine_ID
formControl值:
this.createForm.get('Machine_ID').value
因此,在addSample
中,您可以这样做:
addSample(/*other inputs*/)
const machineIdValue = this.createForm.get('Machine_ID').value;
this.fileService.addSample(/*other inputs*/, machineIdValue).subscribe(() =>
this.router.navigate(['/instruments']);
);
然后您应该更新您的提交按钮:
<form [formGroup]="createForm" class="create-form">
<mat-form-field class="field-full-width">
<mat-label>Instrument</mat-label>
<mat-select matInput formControlName="createForm.get('Machine_ID')" #Machine_ID>
<mat-option *ngFor="let instrument of instruments" [value]="instrument.instrumentName">
instrument.instrumentName
</mat-option>
</mat-select>
</mat-form-field>
</form>
<button (click)="addSample()"
[disabled]="createForm.invalid" mat-raised-button color="primary">Save</button>
以上是关于将要从mat-select表单中绑定的选定值传递给提交按钮功能的主要内容,如果未能解决你的问题,请参考以下文章