如何在ngForm中的'child'指令中添加/获取值?

时间:2017-09-13 16:36:18

标签: angular angular2-forms angular2-directives

拥有以下代码:

<form #carForm="ngForm" (ngSubmit)="createCar(carForm)">
        <div class="form-group">
          <label for="inputCarName">Car Name</label>
          <input [(ngModel)]="name" name="name" type="text">
        </div>
        <div class="form-group">
          <label for="inputPrice">Price</label>
          <input [(ngModel)]="price" name="price" type="number">
        </div>
        <select-inputs-brand></select-inputs-brand>
</form>  

<select-inputs-brand>“child”指令指向以下代码:

<div class="form-group">
  <label for="brandSelect1">Select Brand:</label>
  <select multiple class="form-control" id="brandSelect2">
    <option>Fird</option>
    <option>GM</option>
    <option>Audi</option>
  </select>
</div>
  

如何在<select-inputs-brand>中获取可用选项   我的carForm对象中的指令?

如果需要额外澄清,请告诉我。

提前致谢, Roger A L

1 个答案:

答案 0 :(得分:1)

select-inputs-brand的打字稿代码中,您使用以下选项声明成员变量:

class SelectInputsBrand {
    public options: string[]
    constructor() {
        this.options = ['Ford', 'GM', 'Audi']
    }
}

在您的指令的html中,您将这些选项绑定到UI中的下拉列表:

<select multiple class="form-control" id="brandSelect2">
    <option *ngFor="let o of options">{{ o }}</option>
</select>

carForm的打字稿代码中,您声明了一个包含指令实例的成员变量:

import { ViewChild } from '@angular/core'
import { SelectInputsBrand } from 'wherever/it/is/placed'

export class CarForm {
    @ViewChild('myDropdown') private myDropdown: SelectInputsBrand;

    someFunction() {
        let whatYouNeed = this.myDropdown.options <-- this will give you the options.
    }
}

在你carForm的html中,你给指令一个ID:

<select-inputs-brand #myDropdown></select-inputs-brand>
相关问题