我使用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() }}有什么不對嗎,我得到了這種意想不到的行為。
角度渲染組件首先,然后在 ng-If 中刪除另一個組件
侃侃無極
2022-09-29 17:54:59