1

我试图将选项选择的值返回到我的组件类中,以便稍后进行一些逻辑。但是,它返回为未定义,即使我已将[value]="unit"视图中的值硬编码为选项,当我通过它时,onModelChange(unit)它仍为未定义。基本上我需要给我的表单组实例一个值,但还要获取该字段的值来为另一个字段做一些逻辑。

查看新工作条目

<div  class="card container form-container">
 <div class="row">
   <div class="col-md-12">
    <form (ngSubmit)="createJobEntry(job_entry)" 
        #jobEntryForm="ngForm">

    <div class="form-group">
      <div class="dropdown" dropdown>
      <label class="label-text" for="material" >Material</label>
        <select class="form-control"
                  (ngModelChange)="onMaterialChange($event)"
                  required
                  id="material"
                  name="material"
                [(ngModel)]="job_entry.material" >
          <option  *ngFor=" let m of materials" [ngValue]="m"> {{ 
                    m.product_name }} 
          </option>
        </select>
      </div>
    </div>

<div class="form-group">
<label class="form-group" for="unit" >Unit</label>
  <select class="form-control" id="unit" name="unit" (onModelChange)="onUnitChange(unit)" [(ngModel)]="job_entry.units">
    <option [value]="cm">centimeters</option>
    <option [value]="inch">inches</option>
  </select>
</div>

班级

 job_entry : JobEntry = <JobEntry>{};

  ngOnInit() {

this.job_entry = {
  id: null ,
   client: '',
   material: '',
   size_width: 0 ,
   size_height: 0,
   units: '',
   margin: 0,
   runs: 0,
   prints: 0,
   originals: 0,
   per_print: 0,
   discount: 0,
   price: 0
}

  onMaterialChange(material) {
  alert(material.sell_per_sqm)
  }

onUnitChange(unit) {
alert(unit)
}

我也在控制台中得到了这个:

dom_renderer.ts:311 The specified value "undefined" is not a valid 
number. The value must match to the following regular expression: -?
(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?

任何人都明白这里发生了什么?

4

2 回答 2

3
<option [value]="cm">centimeters</option>
<option [value]="inch">inches</option>

应该是

<option value="cm">centimeters</option>
<option value="inch">inches</option>

或者

<option [value]="'cm'">centimeters</option>
<option [value]="'inch'">inches</option>

否则 Angular 会尝试读取组件类的cminch成员。

于 2017-04-21T10:06:10.743 回答
0

其他选择是:

看法:

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="unitList" ng-change="update()"
        ng-options="unit as unit.label for unit in myunits">           
</select>

<p>Selected: {{unitList.label}}</p>

</div>

控制器:

app.controller('myCtrl', function($scope) {
    $scope.myunits = [{
    value: 'cent',
    label: 'centimeters'
  }, {
    value: 'inch',
    label: 'inches'
  }]; 
  $scope.update = function() {
    console.log($scope.unitList.label)
  }
});

检查这个小提琴

于 2017-04-21T11:07:12.270 回答