2016-07-28 86 views
1

我使用的是角2.0.0-rc.4。Angular2:獲取選定組件中的選定選項

我有一個表單(父組件),並且我在其中有一些其他組件的下拉列表,每個下拉列表有tshtml template否則,每個從其組件中獲取數據。提交表單時,我需要每個選定的值。我如何從父母訪問它?

-Parent HTML表單:

<form class="" (submit)="submitNewModel($event, label.value)"> 
    <div class="form-group"> 
     <label for="label" class="control-label"> Label </label> 
     <input type="text" name="label" #label class="form-control" placeholder="Model's label"> 
    </div> 
    <styles-dropdown></styles-dropdown> 
    <colors-dropdown></colors-dropdown> 
    <modes-dropdown></modes-dropdown> 
    <shapes-dropdown></shapes-dropdown> 
    <button type="submit" name="button">Create new model</button> 
</form> 

-Parent ts

import { Component } from '@angular/core'; 

... 

@Component({ 
    selector: 'models', 
    templateUrl: 'app/models/models.component.html', 
    directives: [ 
    StylesDropDownComponent, 
    ... 
    ] 
}) 
export class ModelsComponent { 

    constructor(){ 
    } 

    submitNewModel(event, label) { 
    event.preventDefault(); 
    console.log('Value label', label); 
    console.log(event); 
    //How do I get selected values here ? 
    } 
} 

-drop下來組件的HTML:

<div class="portlet-body"> 
    <div class="form-group"> 
    <label for="styles" class="control-label"> Style </label> 
    <select name="style-select" id="styles" class="form-control select2"> 
     <option value="">Select style</option> 
     <option *ngFor="let style of styles" value="{{style.id}}">{{ style.label }}</option> 
    </select> 
    </div> 

-drop下來ts

import { Component } from '@angular/core'; 

import { ClientHttp } from '../../common/cigma-http'; 
import { StylesComponent } from '../styles.component'; 

@Component({ 
    selector: 'styles-dropdown', 
    templateUrl: 'app/styles/styles-dropdown/styles.dropdown.component.html', 
}) 
export class StylesDropDownComponent extends StylesComponent { 
    constructor(protected cigmaHttp: CigmaHttp) { 
    super(cigmaHttp) 
    } 
} 

所有其它下拉部件具有相同的結構與上述一個。

回答

0

使用evenEmitter

0

所以玩耍和閱讀一些有益的話題後,通過從父到子組件中的值:

要過時的數據從父嵌套的組件,我們需要使用@Input裝飾:

@Component({ 
    selector: 'child', 
    template: 'child.component.html' 
}) 
export class ChildComponent { 
    @Input() title:string; 
} 

現在我們可以將數據從父項傳遞給該屬性。

@Component({ 
    selector: 'parent', 
    template: 'parent.component.html', 
    directives: [ChildComponent] 
}) 
export class ParentComponent { 
    childTitle:string = 'Information passed to child'; 
} 

,當然還有:

/* parent.component.html */ 
<div> 
    <h1>Parent component</h1> 
    <child[title]='childTitle'></child> 
</div> 

沒有@input裝飾子組件不會知道從父傳遞數據。


並且要將數據從Child傳遞給Parent,我們需要使用eventEmitter。 您可以read more here