Angular組件之間的通訊


communication分支,示范組件之間的通訊

// 使用方法
git clone https://git.oschina.net/mumu-osc/learn-component.git
cd learn-component
git pull origin communication
npm install 
ng serve

1.父子組件之間通訊

// parent-and-child.component.ts
import { Component, OnInit, Input, Output, EventEmitter, AfterViewInit, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
  selector: 'parent-and-child',
  templateUrl: './parent-and-child.component.html',
  styleUrls: ['./parent-and-child.component.css']
})
export class ParentAndChildComponent implements OnInit {
  @ViewChild(ChildComponent)
  private childComponent: ChildComponent;

  constructor() { }

  ngOnInit() {
  }
  
  ngAfterViewInit() {
    //this.childComponent.childFn();
  }

  public doSomething():void{
    alert("收到了子組件的自定義事件!");
  }
}
<!-- parent-and-child.component.html  -->
<div class="panel panel-primary">
    <div class="panel-heading">第一種:父子組件之間通訊</div>
    <div class="panel-body">
        <child #child (follow)="doSomething()" panelTitle="設置子組件標題"></child>
        <button (click)="child.childFn()" class="btn btn-success">調用子組件方法</button>
    </div>
</div>
// child.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  private _panelTitle:string="我是子組件";
  
  @Input()
  set panelTitle(panelTitle:string){
    this._panelTitle="【"+panelTitle+"】";
  }

  get panelTitle():string{
    return this._panelTitle;
  }

  @Output()
  public follow=new EventEmitter<string>();

  constructor() { }

  ngOnInit() {
  }

  public emitAnEvent():void{
    this.follow.emit("follow");
  }

  public childFn():void{
    alert("父組件調用子組件方法!");
  }
}
<!-- child.component.html -->
<div class="panel panel-primary">
  <div class="panel-heading">{{panelTitle}}</div>
  <div class="panel-body">
    <button (click)="emitAnEvent()" class="btn btn-success">觸發一個事件</button>
  </div>
</div>

2.沒有父子關系的組件間通訊

<!-- brother.component.html -->
<div class="panel panel-primary">
  <div class="panel-heading">第二種:沒有父子關系的組件間通訊</div>
  <div class="panel-body">
    <child-1></child-1>
    <child-2></child-2>
  </div>
</div>
// event-bus.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

/**
 * 用來充當事件總線的Service
 */
@Injectable()
export class EventBusService {
  public eventBus:Subject<string> = new Subject<string>();

  constructor() { }

}
// child-1.component.ts
import { Component, OnInit } from '@angular/core';
import { EventBusService } from '../service/event-bus.service';

@Component({
  selector: 'child-1',
  templateUrl: './child-1.component.html',
  styleUrls: ['./child-1.component.css']
})
export class Child1Component implements OnInit {

  constructor(public eventBusService:EventBusService) { }

  ngOnInit() {
  }

  public triggerEventBus():void{
    this.eventBusService.eventBus.next("第一個組件觸發的事件");
  }
}
<!-- child-1.component.html -->
<div class="panel panel-primary">
  <div class="panel-heading">第一個組件</div>
  <div class="panel-body">
    <button (click)="triggerEventBus()" class="btn btn-success">觸發一個事件</button>
  </div>
</div>
// child-2.component.ts
import { Component, OnInit } from '@angular/core';
import { EventBusService } from '../service/event-bus.service';

@Component({
  selector: 'child-2',
  templateUrl: './child-2.component.html',
  styleUrls: ['./child-2.component.css']
})
export class Child2Component implements OnInit {
  public events:Array<any>=[];

  constructor(public eventBusService:EventBusService) {

  }

  ngOnInit() {
    this.eventBusService.eventBus.subscribe((value)=>{
      this.events.push(value+"-"+new Date());
    });
  }
}
<!-- child-2.component.html -->
<div class="panel panel-primary">
  <div class="panel-heading">第二個組件</div>
  <div class="panel-body">
      <p *ngFor="let event of events">{{event}}</p>
  </div>
</div>

3.利用localStorge通訊

<!-- local-storage.component.html -->
<div class="panel panel-primary">
  <div class="panel-heading">第三種方案:利用localStorge通訊</div>
  <div class="panel-body">
    <local-child1></local-child1>
    <local-child2></local-child2>
  </div>
</div>
// local-child1.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'local-child1',
  templateUrl: './local-child1.component.html',
  styleUrls: ['./local-child1.component.css']
})
export class LocalChild1Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  public writeData():void{
    window.localStorage.setItem("json",JSON.stringify({name:'大漠窮秋',age:18}));
  }
}
<!-- local-child1.component.html -->
<div class="panel panel-primary">
  <div class="panel-heading">第一個組件</div>
  <div class="panel-body">
      <button (click)="writeData()" class="btn btn-success">寫數據</button>
  </div>
</div>
// local-child2.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'local-child2',
  templateUrl: './local-child2.component.html',
  styleUrls: ['./local-child2.component.css']
})
export class LocalChild2Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  public readData():void{
    var json=window.localStorage.getItem("json");
    var obj=JSON.parse(json);
    console.log(obj.name);
    console.log(obj.age);
  }
}
<!-- local-child2.component.html -->
<div class="panel panel-primary">
  <div class="panel-heading">第二個組件</div>
  <div class="panel-body">
      <button (click)="readData()" class="btn btn-success">讀數據</button>        
  </div>
</div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM