Angular2官方文档对组件交互这块有详细的介绍-->文档--组件之间的交互。按文档介绍,组件间交互的方式一共有4种,包括:
- 通过输入型绑定把数据从父组件传到子组件(@Input decoration);子组件暴露一个EventEmitter属性(@Output decoration),当事件发生时,利用该属性emits向父组件发射事件。
- 父组件与子组件通过本地变量互动。(# var)
- 父组件调用@ViewChild。
- 父组件和子组件通过服务来通讯。
我在这里只总结、详细介绍3种我在项目中使用过的方法,看完本文大概能做到如下的效果:

创建项目,项目结构如下:

通过@Input、@Output装饰器进行父、子组件间的通信
@Input:该属性绑定用于父组件向子组件传递数据。子组件可以通过以下两种方法截取属性的变更:
- 使用一个输入属性的setter,以拦截父组件中值得变化。
- 通过ngOnchanges()来截听输入属性值的变化。
@Output:该数据绑定用于子组件向父组件传递数据和事件。
<!--parent.component.html-->
<div style="width: 1000px;margin: auto">
<div class="card" style="width: 500px;float: left">
<div class="card-header">
父组件
</div>
<div class="card-body">
<h5 class="card-title">父组件</h5>
<div class="form-group">
<label for="input">父组件输入:</label>
<input type="text"
class="form-control"
id="input"
placeholder="Input something"
[(ngModel)]="parentPrint"
>
<label for="output">父组件输出:</label>
<input type="text"
class="form-control"
id="output"
placeholder="Output something"
[(ngModel)]="contentFromChild"
>
</div>
</div>
</div>
<app-child
[fromParent]="parentPrint"
(fromChild)="fromChild($event)"
></app-child>
</div>
<!--child.component.html-->
<div class="card" style="width: 500px;">
<div class="card-header">
子组件
</div>
<div class="card-body">
<h5 class="card-title">子组件</h5>
<div class="form-group">
<label for="input">子组件输入:</label>
<input type="text"
class="form-control"
id="input"
placeholder="Input something"
[(ngModel)]="contentFromChild"
>
<label for="output">子组件输出:</label>
<input type="text"
class="form-control"
id="output"
placeholder="Output something"
[(ngModel)]="fromParent"
>
</div>
<button class="btn btn-primary" (click)="clickChild()">Output方式</button>
</div>
</div>
内容版权声明:除非注明,否则皆为本站原创文章。
