Angular2 父子组件通信方式的示例(2)
效果如下:(1、父组件输入,子组件可同步输出;2、子组件输入需要(3、)点击按钮触发发射事件,将数据传送给父组件。)

@Input:父组件输入的同时,子组件能同步获取数据进行显示。核心代码如下:
//父组件 parentPrint: any; //ts中,声明一个变量 [(ngModel)]="parentPrint" //html中,绑定变量,获取用户输入 //html中,将数据传给子组件 <app-child [fromParent]="parentPrint"></app-child> //子组件 @Input() fromParent; //ts中,用于直接接收从父组件获取的数据 [(ngModel)]="fromParent" //html中,用于显示数据
通过setter截听输入属性值的变化,在子组件中声明一个私有变量来获取父组件传递过来的数据,从而屏蔽上层获取下层信息。(简单一点就是不让父组件知道子组件用什么东西去接收传过来的数据)通过这种方法也可以获得同样的效果。
//子组件
private _fromParent: any; //私有变量,通过setter获取父组件的数据
@Input() //通过setter获取父组件的数据
set fromParent(fromParent: any) {
this._fromParent = fromParent;
}
get fromParent(): any {
return this._fromParent;
}
@Output:父组件接收子组件的数据时,子组件暴露一个EventEmitter属性,当事件发生时,子组件利用该属性emits(向上弹射)事件。父组件绑定到这个事件属性,并在事件发生时作出回应。核心代码如下:
//子组件
@Output() fromChild = new EventEmitter<any>(); //暴露一个输出属性
<button class="btn btn-primary" (click)="clickChild()">Output方式</button>
//触发发射函数,将数据发送给父组件
clickChild() {
console.log('click child' , this.contentFromChild);
this.fromChild.emit(this.contentFromChild);
}
//父组件
[(ngModel)]="contentFromChild" //绑定输出子组件的数据
//使用子组件,绑定事件属性
<app-child
[fromParent]="parentPrint"
(fromChild)="fromChild($event)"
></app-child>
//事件处理函数
fromChild(event) {
console.log(event);
this.contentFromChild = event;
}
父组件通过调用@ViewChild()来获取子组件的数据
如果父组件的类需要读取子组件的属性和值或调用子组件的方法时,就可以把子组件作为ViewChild,注入到父组件里面。ViewChild顾名思义就是可以看见子组件里面的属性和方法。
<!--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="viewoutput">ViewChild父组件输出:</label>
<input type="text"
class="form-control"
id="viewoutput"
placeholder="ViewChild父组件输出"
[(ngModel)]="viewOutput"
>
</div>
<button class="btn btn-primary" (click)="clickView()">ViewChild方式</button>
</div>
</div>
<app-child></app-child>
</div>
内容版权声明:除非注明,否则皆为本站原创文章。
