使用@ input / @ output angular 2从需要的子节点获取数据

时间:2017-10-13 14:44:06

标签: angular typescript

如何在不使用@viewChild或服务的情况下将对象从子级转换为父级?

export class MultiSelectComponent implements OnInit {

selectedItems: FormSelectComponentOption[] = [];

@Input()
items: FormSelectComponentOption[];

@Output()
selected = new EventEmitter<FormSelectComponentOption[]>();
}

现在,我该怎么做一个&#34;请求&#34;获得一个完整的FormSelectComponentOption?

2 个答案:

答案 0 :(得分:0)

您不会发出请求,而是在每次更改时将选择推送到父组件。
当用户更改MultiSelectComponent中的选项时,您需要调用this.selected.emit(this.selectedItems)并在父级模板中订阅这些更改,例如<multi-select (select)="selectionChanged($event)" [items]="items">,然后在您的父级中订阅selectionChanged()方法这保存了新的选择 当您现在想请求数据时,只需使用您父母保存的选择。

答案 1 :(得分:0)

如果您想在某些事件(例如FormSelectComponentOption[])上将click数据传递给您的父级,则可以使用发射器。

你可以这样做:

//your parent component html
<multi-select (selected)="itemsSelected($event)"></multi-select>

//your parent component class
public class ParentComponent {
  itemsFromChild: FormSelectComponentOption[];

  itemsSelected(FormSelectComponentOption[] items){
    this.itemsFromChild = items;
  }
}

//your child component html
<div (click)="selected.emit(selectedItems);"></div>