We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
适用于层级较近的组件通信
父组件
... @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 是固定写法==
适用于层级较远的组件通信
需求:在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(); } }
==订阅、监听等在组件卸载的时候需要取消、删除==
The text was updated successfully, but these errors were encountered:
No branches or pull requests
1. @input、@output
父组件
子组件
==(sendName)="sendName($event)" 中 $event 是固定写法==
2. 服务
需求:在A组件中推送数据到B组件
服务
A组件推数据
B组件接收数据
==订阅、监听等在组件卸载的时候需要取消、删除==
The text was updated successfully, but these errors were encountered: