这次给大家带来多个组件中进行数据通信angular4,使用多个组件中进行数据通信angular4的注意事项有哪些,下面就是实战案例,一起来看一下。
应用场景,不同组件中操作统一组数据,不论哪个组件对数据进行了操作,其他组件中立马看到效果。这样他们就要共用一个服务实例,是本次的重点,如果不同实例,那么操作的就不是同一组数据,那么就不会有这样的效果,想实现共用服务实例,就是在所有父组件中priviates:[]中引入这个组件,子组件中不需要再次引入,那么他们都是用的父组件中的服务实例。
1、公用服务
import {injectable} from @angular/core;
@injectable()
export class commonservice {
public datelist: any = [
{
name: 张旭超,
age: 20,
address: 北京市朝阳区
}
];
constructor() {
}
adddatefun(data) {
this.datelist.push(data);
}
}
2、parent.component.ts
import {component, oninit} from @angular/core;
import {commonservice} from ./common.service;
// 这里要通过父子公用服务来操作数据,只需要在父组件中引入服务。
@component({
selector: parent-tag,
templateurl: parent.component.html,
providers: [
commonservice
]
})
export class parentcomponent implements oninit {
public list: any = [];
constructor(private commonservice: commonservice) {
this.list = commonservice.datelist;
}
ngoninit() {
}
}
3、parent.component.html
<table width="500">
<tr *ngfor="let item of list">
<td>
{{item.name}}
</td>
<td>
{{item.age}}
</td>
<td>
{{item.address}}
</td>
</tr>
</table>
<child-one-tag></child-one-tag>
4、child-one.component.ts
import {component} from @angular/core;
import {commonservice} from ./common.service;
@component({
selector: child-one-tag,
templateurl: child-one.component.html
})
export class childonecomponent {
public display: boolean = false;
public username: string = ;
public age: number = 20;
public address: string = ;
constructor(public commonservice: commonservice) {
}
showdialog() {
this.display = true;
}
hidedialog() {
this.display = false;
}
addinfofun() {
let params = {
name: this.username,
age: this.age,
address: this.address
};
this.commonservice.adddatefun(params);
params = {};
}
}
5、child-one.component.html
<p-dialog header="弹窗" [(visible)]="display" [width]="300" appendto="body" modal="modal">
<form #myform="ngform" name="myform">
<p>姓名:<input type="text" name="username" [(ngmodel)]="username" pinputtext/></p>
<p>年龄:<input type="number" name="age" [(ngmodel)]="age" pinputtext/></p>
<p>地址:<input type="text" name="address" [(ngmodel)]="address" pinputtext/></p>
<button pbutton label="确定" type="submit" (click)="addinfofun()"></button>
<button pbutton label="取消" (click)="hidedialog()"></button>
</form>
</p-dialog>
<button label="添加" pbutton (click)="showdialog()"></button>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js+canva做出预览压缩和上传图片功能
js怎么存储键值
以上就是多个组件中进行数据通信angular4的详细内容。