在Angular中,可以通過以下幾種方法實現跨組件傳值:
父組件中的傳遞數據示例:
// 父組件中
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);
}
}
子組件中的接收數據示例:
// 子組件中
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');
}
}
創建一個共享的服務:
// 服務中
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
private data: string = '';
setData(data: string) {
this.data = data;
}
getData() {
return this.data;
}
}
在組件中使用服務:
// 組件中
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();
}
}
在路由配置中定義路由參數:
// 路由模塊中
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 { }
在目標組件中獲取路由參數:
// 目標組件中
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'];
});
}
}
通過以上方法,你可以在Angular中實現跨組件傳值。