我使用ngif指令一次显示一个组件。
<app-root>
<first-Comp *ngIf="showFirst"></first-Comp>
<second-Comp *ngIf="!showFirst"></second-Comp>
</app-root>
要点是
显示第一变量使用 true 进行初始化。
第一合成包含高度为100px的元素;
第二比较有动态元素
在第二个组件内部,我使用内部计算高度document.body.scrollHeightngOnInit
问题是当 变为角时,首先呈现第二个合成,然后删除 .结果,我得到的高度是100+而不是0。但是我需要身体的高度,只在组件渲染。showFristfalsefirst-compsecond-comp
我错过了另一件重要的事情,因为我认为这可能不会妨碍。即第一个和第二个组件都与角度自动变化检测分离以提高性能。我有一个这样的基本组件
export class BaseComponent {
private subscriptions: Subscription[] = [];
constructor(private childViewRef: ChangeDetectorRef) {
this.childViewRef.detach();
}
public updateUI(): void {
try {
this.childViewRef.reattach();
this.childViewRef.detectChanges();
this.childViewRef.detach();
} catch (ex) {
// ignored
}
}
protected addSubscriptions(subs: Subscription) {
this.subscriptions.push(subs);
}
protected unSubscribeSubscriptions() {
this.subscriptions.forEach(item => item.unsubscribe());
this.subscriptions = [];
}
}
除应用程序组件外,所有组件都继承此基本组件,因此第二组件的代码如下所示。
@Component({
selector: 'second-comp',
templateUrl: './SecondComponent.component.html',
styleUrls: ['./SecondComponent.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SecondComponent extends BaseComponent implements OnInit, AfterViewInit{
constructor(private ref:ChangeDetectorRef){
super(ref);
}
ngAfterViewInit(): void {
this.updateUi();
this.publishHeight()
}
ngOnInit() {
this.updateUi();
this.publishHeight()
}
}
有什么不对吗,我得到了这种意想不到的行为。
侃侃无极
婷婷同学_
慕田峪7331174
HUH函数
随时随地看视频慕课网APP
相关分类