http://www.cnblogs.com/SLchuck/p/5904000.html
https://i.cnblogs.com/EditPosts.aspx?postid=7995179&update=1
https://segmentfault.com/a/1190000010048073
agular5 父子組件之間傳值是實用
- 第一類:父子組件間的通信
- @Input 和@Output
當然一般傳值變化是指父組件像子組件傳的值變化的情況,如地圖zoom變化
當篩選范圍變化時地圖比例尺變化地圖隨着縮放,這是地圖控件就要監聽父組件的篩選范圍值變化
import {
Component,
OnInit,
Input,
Output,
EventEmitter,
OnDestroy,
ElementRef,
OnChanges,
SimpleChanges
} from '@angular/core';
/*import {loader} from './loader';*/
/*import {BAIDU_MAP_STYLE} from './map';*/
/*import any = jasmine.any;*/
declare const BMap: any;
@Component({
selector: 'app-baidu-map',
templateUrl: './baidu-map.component.html',
styleUrls: ['./baidu-map.component.css']
})
export class BaiduMapComponent implements OnInit, OnChanges {
@Input() address: string = '深圳';
@Input() apiKey: string = 'sIq3pmhG5n4xVuKQ8eKr1BiV0hsLP2ek';
@Input() center: any;
@Input() zoom = 15;
@Input() enableScrollWheelZoom = false; //鼠標是否可滾動縮放 默認不可以
@Input() zoomControl = false; //是否有縮放控件 默認沒有
@Output() getLocation: EventEmitter<any> = new EventEmitter();
geoAddress = '';
constructor(private elementRef: ElementRef) {
}
ngOnInit() {
//不需要init because zoom一進來就變化了就觸發onChange函數執行loader去initMap了所以此處不需要loader
/* var address = this.geoAddress ? this.geoAddress : this.address;
loader(this.apiKey, this.initMap.bind(this,address));*/
}
ngOnChanges(changes: SimpleChanges) {
//當zoomlevel改變刷新地圖時marker不需要初始化位最開始定位的
var address = this.geoAddress ? this.geoAddress : this.address;
this.loader(this.apiKey, this.initMap.bind(this, address));
}
}
這樣就可以監聽了(注意標紅的代碼)
- forwardref(父獲得子實例)
import { Component, Input, EventEmitter, Output,Host,Inject,forwardRef } from '@angular/core';
import{ParentPage} from '../parent/parent';
@Component({
selector: 'page-child',
templateUrl: 'child.html',
})
export class ChildPage {
constructor( @Host() @Inject(forwardRef(() => ParentPage)) app: ParentPage) {
setInterval(() => {
app.i++;
}, 1000);
}
}
- @viewChild(父獲得實例)
import {ViewChild, Component } from '@angular/core';
import{ChildPage}from '../child/child';
@Component({
selector: 'page-parent',
templateUrl: 'parent.html',
})
export class ParentPage {
@ViewChild(ChildPage) child:ChildPage;
ngAfterViewInit() {
setInterval(()=> {
this.child.i++;
}, 1000)
}
}
共用一個service
subject
eventEmitter