我使用的是角度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>
-Drop down 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 :(得分:0)
使用evenEmitter将值从父组件传递给子组件
答案 1 :(得分: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。