Skip to content

Angular 组件间通信方法总结 #60

Open
@deepthan

Description

@deepthan

1. @input@output

适用于层级较近的组件通信

父组件

...
@Component({
  selector: 'parent',
  template: `
    <son [name]="name" (sendName)="sendName($event)"></son>
  `,
})

export class ParentComponent {
    name = "momomo";
    
    sendName(newName:string){
        // newName是子组件传递回来的
    }
}

子组件

import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
  selector: 'son',
  template: `
   <p> {{ name }} </p>
   <button (click)="modifyName()"></button>
  `,
})

export class ParentComponent {
    @Input() name:string;
    @Output() sendName = new EventEmitter<string>();
    
    modifyName(){
        this.sendName.emit('deepthan');
    }
}

==(sendName)="sendName($event)" 中 $event 是固定写法==

2. 服务

适用于层级较远的组件通信

需求:在A组件中推送数据到B组件

服务

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class NameService {
  name$ = new Subject<any>();

  sendName(name:string) {
    this.name$.next(name);
  }
}

A组件推数据

import { NameService } from 'xxx';
...
export class AComponent{
    constructor( private nameSrv: NameService) {
        this.nameSrv.sendName('momomo');
    }
}

B组件接收数据

import { Subscription } from 'rxjs';
import { NameService } from 'xxx';
...
export class BComponent implements OnDestroy{
    nameSub: Subscription;
    
    constructor( private nameSrv: NameService) {
        this.nameSub = this.nameSrv.name$.subscribe((name) => {
            // 接收到推送的数据
        }
    }
    
    ngOnDestroy() {
        this.nameSub.unsubscribe();
    }
}

==订阅、监听等在组件卸载的时候需要取消、删除==

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions