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

转载于:https://www.cnblogs.com/mttcug/p/7995179.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值