本文主要介绍angular在不同的组件中如何进行传值,如何通讯。主要分为父子组件和非父子组件部分。
父子组件间参数与通讯方法
使用事件通信(EventEmitter,@Output):
场景:可以在父子组件之间进行通信,一般使用在子组件传递消息给父组件;
步骤:
代码:
// child 组件 @Component({ selector: 'app-child', template: '', styles: [``] }) export class AppChildComponent implements OnInit { @Output() onVoted: EventEmitter<any> = new EventEmitter(); ngOnInit(): void { this.onVoted.emit(1); } } // parent 组件 @Component({ selector: 'app-parent', template: ` <app-child (onVoted)="onListen($event)"></app-child> `, styles: [``] }) export class AppParentComponent implements OnInit { ngOnInit(): void { throw new Error('Method not implemented.'); } onListen(data: any): void { console.log('TAG' + '---------->>>' + data); } }
使用@ViewChild和@ViewChildren:
场景:一般用于父组件给子组件传递信息,或者父组件调用子组件的方法;
步骤:
代码:
// 子组件@Component({ selector: 'app-child', template: '', styles: [``]})export class AppChildComponent2 implements OnInit { data = 1; ngOnInit(): void { } getData(): void { console.log('TAG' + '---------->>>' + 111); }}// 父组件@Component({ selector: 'app-parent2', template: ` <app-child></app-child> `, styles: [``]})export class AppParentComponent2 implements OnInit { @ViewChild(AppChildComponent2) child: AppChildComponent2; ngOnInit(): void { this.child.getData(); // 父组件获得子组件方法 console.log('TAG'+'---------->>>'+this.child.data);// 父组件获得子组件属性 }}
非父子组件参数传递与通讯方法
通过路由参数
场景:一个组件可以通过路由的方式跳转到另一个组件 如:列表与编辑
步骤:
此方法只适用于参数传递,组件间的参数一旦接收就不会变化
代码
传递方式
routerLink
<a routerLink=["/exampledetail",id]></a>routerLink=["/exampledetail",{queryParams:object}]routerLink=["/exampledetail",{queryParams:'id':'1','name':'yxman'}];
router.navigate
this.router.navigate(['/exampledetail',id]);this.router.navigate(['/exampledetail'],{queryParams:{'name':'yxman'}});
新闻热点
疑难解答
图片精选