2016-07-28 14 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

に値を渡すために:ネストされたコンポーネントに親からデータをPASSEするに

を、私たちは@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デコレータ子コンポーネントがなければ文句を言わない親から渡されたデータのことを知っています。


子から親にデータを渡すには、eventEmitterを使用する必要があります。 read more hereとすることができます。

関連する問題