angular5 組件之間監聽傳值變化

http://www.cnblogs.com/SLchuck/p/5904000.htmlcss

 https://i.cnblogs.com/EditPosts.aspx?postid=7995179&update=1html

http://www.javashuo.com/article/p-khvpvxvp-n.htmlsegmentfault

agular5 父子組件之間傳值是實用api

  • 第一類:父子組件間的通訊
  1. @Input 和@Output

固然通常傳值變化是指父組件像子組件傳的值變化的狀況,如地圖zoom變化app

當篩選範圍變化時地圖比例尺變化地圖隨着縮放,這是地圖控件就要監聽父組件的篩選範圍值變化函數

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));
}
}

這樣就能夠監聽了(注意標紅的代碼


  1. 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);
}
}post

 

 

  1. @viewChild(父得到實例)

import {ViewChild, Component } from '@angular/core';
import{ChildPage}from '../child/child';this

@Component({
selector: 'page-parent',
templateUrl: 'parent.html',
})
export class ParentPage {
@ViewChild(ChildPage) child:ChildPage;
ngAfterViewInit() {
setInterval(()=> {
this.child.i++;
}, 1000)
}
}spa

 

共用一個servicecomponent

subject

eventEmitter

相關文章
相關標籤/搜索