Angular組件傳值方法

一.組件之間傳值的方法

1.父子組件之間的傳值方法

1.1 @InInput和@Output方法
export class testExample implements OnInit{
	@Input test:any = {};
	@Output testFun = new EventEmitter<any>();
}

複製代碼
<test-example [test]="test" (testFun)="testFun($event)"></test-example>
複製代碼

@Input修飾的變量爲父組件傳入子組件的輸入屬性. @Outpue修飾的子組件傳入父組件的輸出屬性.bash

1.2 inputs和outputs

@Component({
     //...
    inputs:['test'],
    outputs:['testFun']
})
 
export class testExample implements OnInit{
    test:any = {};
    testFun = new 	EventEmitter<any>();
}
複製代碼
1.3 @ViewChild,父組件獲取子組件的引用
import { Component,AfterViewInit,ViewChild } from '@angular/core';
@Component({
    selector:'collection',
    template:`
        <contact-collect (click)="collectTheContact()"></contact-collect>
    `
})
export class CollectionComponent {
    @ViewChild(ContactCollectComponent) contactCollect: ContactCollectComponent;
    ngAfterViewInit(){
        //...
    }
     
    collectTheContact(){
        this.contactCollect.collectTheContact();
    }
}
複製代碼

ViewChild是屬性裝飾器,用來從模板視圖中獲取匹配的元素.視圖查詢在ngAfterViewInit鉤子函數調用前完成,所以在ngAfterViewInit鉤子函數中,就能正常獲取查詢的元素. ViewChildren裝飾器用來從模板中獲取匹配的多個元素,返回的結果是一個QueryList集合, 使用模板變量名設置查詢條件cookie

1.4 局部變量,父組件獲取子組件引用
template:`
        <contact-collect (click)="collectTheContact()" #collect></contact-collect>
複製代碼

綁定局部變量collect(以#號標記),以此來獲取子組件類的實例對象.session

2.非父子組件之間傳值

2.1 service

須要雙向的觸發(發送信息/接收信息)函數

service.ts
import { Component, Injectable, EventEmitter } from "@angular/core";
@Injectable()
export class myService {
  public info: string = "";
  constructor() {}
}
複製代碼

組件1向service傳遞信息ui

import { myService } from '../../service/myService.service';
...
constructor(
  public service: myService
) { }

changeInfo() {
  this.service.info = this.service.info + "1234";
}
...
複製代碼

組件2從service獲取信息this

import { myService } from '../../service/myService.service';
...
constructor(
  public service: myService
) { }

showInfo() {
  alert(this.service.info);
}
...
複製代碼
2.2 使用BehaviorSubject

發佈者訂閱者模式,當數據改變時,訂閱者也能獲得響應url

servicespa

import { BehaviorSubject } from 'rxjs';
...
public messageSource = new BehaviorSubject<string>('Start');
changemessage(message: string): void {
  this.messageSource.next(message);
}
複製代碼

組件調用service的方法傳信息和接收信息code

changeInfo() {
  this.communication.changemessage('Message from child 1.');
}
ngOnInit() {
  this.communication.messageSource.subscribe(Message => {
    window.alert(Message);
    this.info = Message;
  });
}
複製代碼
2.3 路由傳值
2.3.1 在查詢參數中傳遞
複製代碼
//傳遞數據
...
<a [routerLink]="['/stock']" [queryParams]="{id: 1}">股票詳情</a>
// http://localhost:4200/stock?id=1



//接受參數
...
import { ActivatedRoute } from '@amgular/router';

export class StockComponent implements OnInit {

    private stockId: number;    
    
    constructor(private routeInfo: ActivatedRoute)
    
    ngOnInit() {
        this.stockId = this.routeInfo.snapshot.queryParams['id'];
    }
    
}
複製代碼
2.3.2 在路由路徑中傳遞
複製代碼
//修改配置
const routes: Routes = [
  {path: '', redirectTo: '/index', pathMatch: 'full'},
  {path: 'index', component: IndexComponent},
  {path: 'stock/:id', component: StocksComponent },
  {path: '**', component: ErrorPageComponent }
];


//傳遞數據
...[
](url)<a [routerLink]="['/stock', 1]">股票詳情</a>
// http://localhost:4200/stock/1



//接受參數
...
import { ActivatedRoute } from '@amgular/router';

export class StockComponent implements OnInit {

    private stockId: number;    
    
    constructor(private routeInfo: ActivatedRoute)
    
    ngOnInit() {
        this.stockId = this.routeInfo.snapshot.params['id'];
    }
    
}
複製代碼
2.3.3 在路由配置中傳遞
複製代碼
//路由配置配置
const routes: Routes = [
  {path: '', redirectTo: '/index', pathMatch: 'full'},
  {path: 'index', component: IndexComponent, data: {title: 'Index Page'}},
  {path: 'stock/:id', component: StocksComponent, data: {title: 'Stock Page'}},
  {path: '**', component: ErrorPageComponent, data: {title: 'Stock Page'}}
];


//接受參數
this.title = this.routeInfo.snapshot.date[0]['title'];
複製代碼
其它傳值方式

cookie、session、storagecomponent

相關文章
相關標籤/搜索