angular5 组件之间监听传值变化

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

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

https://segmentfault.com/a/1190000010048073

agular5 父子组件之间传值是实用

  • 第一类:父子组件间的通信
  1. @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));
}
}

这样就可以监听了(注意标红的代码


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

 

 

  1. @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

posted @ 2017-12-06 22:14  上帝不是要你成功,而是让你去尝试  阅读(6137)  评论(0编辑  收藏  举报