【发布时间】:2017-03-08 16:44:02
【问题描述】:
当我按下“隐藏”按钮时,我有一个 div 会改变高度。
我已经通过服务(如cookbook)捕获了这种高度变化,当我按下“获取高度”按钮时,我得到了正确给出的值变化。
但我想看看我是否可以在不每次按下按钮的情况下获得高度值。这意味着我正在尝试实现一个 ngOnChanges 挂钩以查看高度何时发生变化,然后在新高度发生变化时将其记录到控制台。
但是我没有从我的 ngOnChanges 钩子中得到任何响应,即使我已经查看了关于它的每个问题并尝试以相同的方式实现它。
我的组件
import { Component, SimpleChanges } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { MissionService } from '../../main2/mission.service';
@Component({
selector: 'test-child3',
templateUrl: './child3.component.html',
styleUrls: ['./child3.component.css']
})
export class Child3Component {
private switch1 = false;
height: number;
subscription: Subscription;
constructor(private missionService: MissionService) {
this.subscription = missionService.missionHeight$.subscribe(
missionData => {
this.height = missionData;
console.log("constructor height = " + this.height)
})
}
ngOnChanges(changes: SimpleChanges) {
if (changes['height'].currentValue) {
console.log("ngOnChanges height = " + this.height);
}
}
heightF() {
this.height = document.getElementById('mainDiv').offsetHeight;
this.missionService.announceHeight(this.height);
console.log("heightF() height = " + this.height);
}
onSwitch1() {
this.switch1 = !this.switch1;
}
我的 HTML
<div id="mainDiv">
<button id="hide" (click)="onSwitch1()">Hide</button>
<button (click)="heightF()">Get Height</button>
<div *ngIf="switch1" id="childDiv">
</div>
</div>
这是我每次隐藏/取消隐藏内部 div,然后按“获取高度”按钮时得到的 concole 响应,所以我知道我的观察者正在工作并改变高度。
constructor height = 21
heightF() height = 21
constructor height = 198
heightF() height = 198
【问题讨论】:
标签: angular