2017-09-13 3 views
0

Avoir le code suivant:Comment ajouter/obtenir des valeurs d'une directive 'child' dans un ngForm?

<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> 

les <select-inputs-brand> points de directive "enfant" au code suivant:

<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> 

Comment puis-je obtenir les options disponibles dans <select-inputs-brand> directive dans mon objet carForm ?

En cas de clarification supplémentaire nécessaire, s'il vous plaît faites le moi savoir.

Merci à l'avance, Roger AL

Répondre

1

Dans votre code tapuscrit l » de select-inputs-brand vous déclarez une variable membre avec les options:

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

Dans la html de votre directive vous liez ces options à la déroulant dans l'interface utilisateur:

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

dans le code tapuscrit de carForm vous déclarez une variable membre qui tiendra l'instance de la directive:

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. 
    } 
} 

Dans le code html de votre carForm vous donner la directive un ID:

<select-inputs-brand #myDropdown></select-inputs-brand>