本文主要介紹angular在不同的組件中如何進(jìn)行傳值,如何通訊。主要分為父子組件和非父子組件部分。
父子組件間參數(shù)與通訊方法
使用事件通信(EventEmitter,@Output):
場景:可以在父子組件之間進(jìn)行通信,一般使用在子組件傳遞消息給父組件;
步驟:
代碼:
// 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:
場景:一般用于父組件給子組件傳遞信息,或者父組件調(diào)用子組件的方法;
步驟:
代碼:
// 子組件@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);// 父組件獲得子組件屬性 }}非父子組件參數(shù)傳遞與通訊方法
通過路由參數(shù)
場景:一個組件可以通過路由的方式跳轉(zhuǎn)到另一個組件 如:列表與編輯
步驟:
此方法只適用于參數(shù)傳遞,組件間的參數(shù)一旦接收就不會變化
代碼
傳遞方式
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'}});
新聞熱點
疑難解答
圖片精選