为了账号安全,请及时绑定邮箱和手机立即绑定

角度渲染组件首先,然后在 ng-If 中删除另一个组件

角度渲染组件首先,然后在 ng-If 中删除另一个组件

侃侃无极 2022-09-29 17:54:59
我使用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()   }}有什么不对吗,我得到了这种意想不到的行为。
查看完整描述

3 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

计算在 ngOn 初始化内的第二次合成中设置超时() 中的高度

 setTimeout(() => { 
          //calculateHeight()  
        }, 200);



查看完整回答
反对 回复 2022-09-29
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

感觉你做错了。您可以在第二复合构造函数中注入@Self,它将为您提供自身的元素Ref(第二复合)。


constructor( @Self() private element: ElementRef ) {}

它可能不起作用,但不会受到第一次竞争的影响


ngOnInit() {

    this.element.nativeElement.offsetHeight //the height for whatever you need it for

}


查看完整回答
反对 回复 2022-09-29
?
HUH函数

TA贡献1836条经验 获得超4个赞

您应该计算组件视图完全呈现时的高度。这意味着计算 ng 内部的高度后查看初始化() 钩子。请参阅 https://angular.io/api/core/AfterViewInit


查看完整回答
反对 回复 2022-09-29
  • 3 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号