首页 > 语言 > JavaScript > 正文

angular中不同的组件间传值与通信的方法

2024-05-06 15:24:51
字体:
来源:转载
供稿:网友

本文主要介绍angular在不同的组件中如何进行传值,如何通讯。主要分为父子组件和非父子组件部分。

父子组件间参数与通讯方法

使用事件通信(EventEmitter,@Output):

场景:可以在父子组件之间进行通信,一般使用在子组件传递消息给父组件;

步骤:

    子组件创建事件EventEmitter对象,使用@output公开出去; 父组件监听子组件@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:

场景:一般用于父组件给子组件传递信息,或者父组件调用子组件的方法;

步骤:

    父组件里面使用子组件; 父组件里面使用@ViewChild获得子组件对象。 父组件使用子组件对象操控子组件;(传递信息或者调用方法)。

代码:

// 子组件@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);// 父组件获得子组件属性 }}

非父子组件参数传递与通讯方法

通过路由参数

场景:一个组件可以通过路由的方式跳转到另一个组件 如:列表与编辑

步骤:

    A组件通过routerLink或router.navigate或router.navigateByUrl进行页面跳转到B组件 B组件接受这些参数

此方法只适用于参数传递,组件间的参数一旦接收就不会变化

代码

传递方式

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'}});            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选