国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

angular中不同的組件間傳值與通信的方法

2024-05-06 15:24:51
字體:
供稿:網(wǎng)友

本文主要介紹angular在不同的組件中如何進(jìn)行傳值,如何通訊。主要分為父子組件和非父子組件部分。

父子組件間參數(shù)與通訊方法

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

場景:可以在父子組件之間進(jìn)行通信,一般使用在子組件傳遞消息給父組件;

步驟:

    子組件創(chuàng)建事件EventEmitter對象,使用@output公開出去; 父組件監(jiān)聽子組件@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:

場景:一般用于父組件給子組件傳遞信息,或者父組件調(diào)用子組件的方法;

步驟:

    父組件里面使用子組件; 父組件里面使用@ViewChild獲得子組件對象。 父組件使用子組件對象操控子組件;(傳遞信息或者調(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)到另一個組件 如:列表與編輯

步驟:

    A組件通過routerLink或router.navigate或router.navigateByUrl進(jìn)行頁面跳轉(zhuǎn)到B組件 B組件接受這些參數(shù)

此方法只適用于參數(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'}});            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 沾化县| 恭城| 民丰县| 皋兰县| 柳江县| 岳普湖县| 郯城县| 沅江市| 上蔡县| 台州市| 丰台区| 巧家县| 胶南市| 扬中市| 潮安县| 西峡县| 岳池县| 西乡县| 佛学| 永寿县| 石林| 富宁县| 新野县| 江城| 容城县| 惠州市| 五家渠市| 金湖县| 开江县| 定日县| 吴江市| 望都县| 张掖市| 乡城县| 吴堡县| 扎兰屯市| 拜泉县| 神池县| 山西省| 丰城市| 山阳县|