angular跨組件傳值怎么實(shí)現(xiàn)

小億
128
2023-11-20 20:38:03
欄目: 編程語言

在Angular中,可以使用以下幾種方法實(shí)現(xiàn)跨組件傳值:

  1. 利用@Input和@Output裝飾器:通過在子組件中使用@Input裝飾器接收父組件傳遞的值,然后通過@Output裝飾器將子組件的值傳遞給父組件。

    父組件:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-parent',
      template: `
        <h1>Parent Component</h1>
        <app-child [childValue]="parentValue" (childEvent)="handleChildEvent($event)"></app-child>
      `
    })
    export class ParentComponent {
      parentValue: string;
    
      handleChildEvent(event: string) {
        console.log(event);
      }
    }
    

    子組件:

    import { Component, Input, Output, EventEmitter } from '@angular/core';
    
    @Component({
      selector: 'app-child',
      template: `
        <h2>Child Component</h2>
        <input [(ngModel)]="childValue" (input)="childEvent.emit(childValue)">
      `
    })
    export class ChildComponent {
      @Input() childValue: string;
      @Output() childEvent = new EventEmitter<string>();
    }
    
  2. 使用服務(wù)(Service):創(chuàng)建一個(gè)共享的服務(wù),將要傳遞的值存儲(chǔ)在該服務(wù)中,然后在需要訪問該值的組件中注入該服務(wù)。

    共享服務(wù):

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class SharedService {
      sharedValue: string;
    }
    

    組件1:

    import { Component } from '@angular/core';
    import { SharedService } from './shared.service';
    
    @Component({
      selector: 'app-component1',
      template: `
        <h1>Component 1</h1>
        <input [(ngModel)]="sharedService.sharedValue">
      `
    })
    export class Component1Component {
      constructor(public sharedService: SharedService) {}
    }
    

    組件2:

    import { Component } from '@angular/core';
    import { SharedService } from './shared.service';
    
    @Component({
      selector: 'app-component2',
      template: `
        <h2>Component 2</h2>
        <p>{{ sharedService.sharedValue }}</p>
      `
    })
    export class Component2Component {
      constructor(public sharedService: SharedService) {}
    }
    
  3. 使用路由參數(shù):通過在URL中傳遞參數(shù),不同組件之間可以通過路由參數(shù)進(jìn)行通信。

    路由配置:

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { Component1Component } from './component1.component';
    import { Component2Component } from './component2.component';
    
    const routes: Routes = [
      { path: 'component1/:value', component: Component1Component },
      { path: 'component2/:value', component: Component2Component },
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    組件1:

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    
    @Component({
      selector: 'app-component1',
      template: `
        <h1>Component 1</h1>
        <p>Value: {{ value }}</p>
      `
    })
    export class Component1Component implements OnInit {
      value: string;
    
      constructor(private route: ActivatedRoute) {}
    
      ngOnInit() {
        this.route.params.subscribe(params => {
          this.value = params['value'];
        });
      }
    }
    

    組件2:

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    
    @Component({
      selector: 'app-component2',
      template: `
        <h2>Component 2</h2>
        <p>Value: {{ value }}</p>
      `
    })
    export class Component2Component implements OnInit {
      value: string;
    
      constructor(private route: ActivatedRoute) {}
    
      ngOnInit() {
        this.route.params.subscribe(params => {
          this.value = params['value'];
        });
      }
    }
    

這些方法都可以實(shí)現(xiàn)跨組件傳值,具體選擇哪種方法

0