我在上上篇文章中介紹了父子組件間經過 Input 和 Output 的交流方式。如今我會介紹組件間交流的其餘兩種方法,viewChild 和 data service。我將這篇文章分爲兩部分。首先看 viewChild 部分吧。css
viewChild 就是准許一個組件被注入到別的組件中。而且指明瞭該可用子組件有了通往父組件的通道。簡單說來,就是若是咱們想要子組件的特性,咱們就可使用 viewChild 這個神器。爲了講得詳細點,如下面的代碼爲例。先建立兩個組件,一個爲父組件,另外一個爲子組件。 下面是 child.component.tshtml
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { counter :number = 0; IncreaseNumber():void{ this.counter++; } constructor() { } ngOnInit() { } }
從這個代碼塊中,咱們能夠知道,該組件有一個 counter 屬性和一個 IncreaseNumber 方法。每次調用 IncreaseNumber 方法,counter的值就會自增一次。如今咱們看看父組件。 parent.component.tstypescript
import { Component, OnInit, ViewChild } from '@angular/core'; import{ChildComponent} from './child.component' @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { @ViewChild(ChildComponent) private childcomponent : ChildComponent; Increase():void{ this.childcomponent.IncreaseNumber(); } Dicrease():void{ this.childcomponent.counter--; } constructor() { } ngOnInit() { } }
如今一步步分析上面的代碼塊。app
@ViewChild(ChildComponent) private childcomponent : ChildComponent;ide
這句代碼很是重要,用於查詢子組件,並在本地建立的子組件對象 childcomponent 中注入相同的屬性。父組件一樣有兩個方法,自增和自減。父組件的模板能夠改爲這樣子:this
<p> <b>@ViewChild with Components..</b> <br> <br> <input type="button" (click)="Increase()"> <input type="button" (click)="Decrease()"> <app-child></app-child> </p>
能夠看到,咱們在父組件模板中實例化了子組件。code
到目前爲止,咱們已經知道了如何在相關組件間傳遞數據,那麼若是是不想關的組件呢?咱們一般會用 service 來實現數據傳遞。共享數據背後的思想是共享服務,他將全部被組件中用到的數據同步在一塊兒。就像下面這個例子: 首先來個data service:Data.service.tscomponent
import { Injectable } from '@angular/core'; import {BehaviorSubject} from 'rxjs' @Injectable() export class DataService { private messageSource = new BehaviorSubject < string > ("Start"); constructor() {} changemessage(message: string): void { this.messageSource.next(message); } }
如今咱們來分析一下上面這個代碼塊:htm
import { Component, OnInit } from '@angular/core'; import{DataService} from '../data.service'; @Component({ selector: 'app-secondcomponent', templateUrl: './secondcomponent.component.html', styleUrls: ['./secondcomponent.component.css'] }) export class SecondcomponentComponent implements OnInit { childmessage: string = ""; counter:number = 0; constructor(private data: DataService) {} ngOnInit() { this.data.currentmessage.subscribe(Message => this.childMessage); } newmessage(): void { this.data.changemessage("changing counter from sibling " + this.counter++); } }
總結:對象
參考:https://dzone.com/articles/angular-component-communication-day-2