阅读 533

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修饰的子组件传入父组件的输出属性.

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集合, 使用模板变量名设置查询条件

1.4 局部变量,父组件获取子组件引用
template:`
        <contact-collect (click)="collectTheContact()" #collect></contact-collect>
复制代码

绑定局部变量collect(以#号标记),以此来获取子组件类的实例对象.

2.非父子组件之间传值

2.1 service

需要双向的触发(发送信息/接收信息)

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

组件1向service传递信息

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

changeInfo() {
  this.service.info = this.service.info + "1234";
}
...
复制代码

组件2从service获取信息

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

showInfo() {
  alert(this.service.info);
}
...
复制代码
2.2 使用BehaviorSubject

发布者订阅者模式,当数据改变时,订阅者也能得到响应

service

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

组件调用service的方法传信息和接收信息

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、storage