在Angular中,可以通過(guò)以下幾種方法實(shí)現(xiàn)跨組件傳值:
父組件中的傳遞數(shù)據(jù)示例:
// 父組件中
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child [data]="parentData" (dataEvent)="receiveData($event)"></app-child>
`
})
export class ParentComponent {
parentData: string = 'Hello World';
receiveData(data: string) {
console.log(data);
}
}
子組件中的接收數(shù)據(jù)示例:
// 子組件中
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<p>{{ data }}</p>
<button (click)="sendData()">Send Data</button>
`
})
export class ChildComponent {
@Input() data: string;
@Output() dataEvent: EventEmitter<string> = new EventEmitter<string>();
sendData() {
this.dataEvent.emit('Data from child component');
}
}
創(chuàng)建一個(gè)共享的服務(wù):
// 服務(wù)中
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
private data: string = '';
setData(data: string) {
this.data = data;
}
getData() {
return this.data;
}
}
在組件中使用服務(wù):
// 組件中
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-parent',
template: `
<p>{{ data }}</p>
<button (click)="setData()">Set Data</button>
`,
providers: [DataService]
})
export class ParentComponent {
data: string = '';
constructor(private dataService: DataService) {}
setData() {
this.dataService.setData('Data from parent component');
}
ngOnInit() {
this.data = this.dataService.getData();
}
}
在路由配置中定義路由參數(shù):
// 路由模塊中
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ChildComponent } from './child.component';
const routes: Routes = [
{ path: 'child/:data', component: ChildComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在目標(biāo)組件中獲取路由參數(shù):
// 目標(biāo)組件中
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-child',
template: `
<p>{{ data }}</p>
`
})
export class ChildComponent {
data: string = '';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
this.data = params['data'];
});
}
}
通過(guò)以上方法,你可以在Angular中實(shí)現(xiàn)跨組件傳值。