[英]Angular2: Get selected option in select component
我正在使用角度2.0.0-rc.4。
我有一個表單(父組件),我有一些來自其他組件的下拉列表,每個下拉列表都有ts
和html template
,其中每個都從其組件中獲取數據。 提交表單時,我需要每個表格的選定值。 如何從父母那里訪問它?
- 表單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 down組件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>
- 下降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)
}
}
所有其他下拉組件具有與上述相同的結構。
使用evenEmitter將值從父組件傳遞給子組件
所以在玩完並閱讀一些有用的主題之后:
要將數據從父級傳遞到嵌套組件,我們需要使用@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。 你可以在這里閱讀更多 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.