从NgForm中获取选定的值

时间:2018-05-06 16:36:31

标签: angular typescript firebase

我有一个名为dashboard.component.html的组件,它只包含一个表单中的四个选择框。我有一个按钮,在dashboard.component.ts中触发一个名为onSubmit()的函数。我需要将表单中的选定值传递给onSubmit(),然后将这些值传递给服务。我似乎无法获得所选的值 - 当我将它们打印到控制台时,我得到[object Object]。

dashboard.component.html:

print(f"  {board[x]} | {board[x+1]} | {board[x+2]}")

dashboard.component.ts(仅限相关部分):

    <form (ngSubmit)="onSubmit(escortForm)" #escortForm="ngForm">
<div class="form-group">
  <select class="form-control" id="driver" name="driver" #name="ngModel" [(ngModel)]="selectedValue">
    <option *ngFor="let driver of drivers" [value]="driver">{{driver.viewValue}}</option>
  </select>
</div>
<div class="form-group">
  <select class="form-control" id="pickup" name="pickup" #name="ngModel" [(ngModel)]="escortService.selectedEscort.pickup">
    <option *ngFor="let location of locations" [value]="location">{{location.viewValue}}</option>
  </select>
</div>
<div class="form-group">
  <select class="form-control" id="dropoff" name="dropoff" #name="ngModel" [(ngModel)]="escortService.selectedEscort.dropoff">
    <option *ngFor="let location of locations" [value]="location">{{location.viewValue}}</option>
  </select>
</div>
<div class="form-group">
  <select class="form-control" id="numPsngers" name="passenger" #name="ngModel" [(ngModel)]="escortService.selectedEscort.passengers">
    <option *ngFor="let passenger of passengers" [value]="passenger">{{passenger.viewValue}}</option>
  </select>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>

escort.service.ts:

import { Component, OnInit } from '@angular/core';
import * as Chartist from 'chartist';
import { FormsModule }   from '@angular/forms';
import { NgForm } from '@angular/forms';
import { EscortService } from './shared/escort.service';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
declare var $:any;
declare var google: any;

@Component({
    selector: 'dashboard-cmp',
    moduleId: module.id,
    templateUrl: 'dashboard.component.html',
    providers: [EscortService]
})

export class DashboardComponent implements OnInit{

    constructor(private escortService : EscortService, private firebase : AngularFireDatabase) { }

onSubmit(escortForm: NgForm){
       this.escortService.newEscort(escortForm.value);
    }

1 个答案:

答案 0 :(得分:1)

由于select项值似乎是对象,因此应使用[ngValue]而不是[value]设置它们:

<div class="form-group">
  <select class="form-control" id="pickup" name="pickup" #name="ngModel" [(ngModel)]="escortService.selectedEscort.pickup">
    <option *ngFor="let location of locations" [ngValue]="location">{{location.viewValue}}</option>
  </select>
</div>