* ng如果Angular中的DOM更新计时问题 [英] *ngIf DOM update timing issue in Angular

查看:87
本文介绍了* ng如果Angular中的DOM更新计时问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<ng-container *ngIf="show">
  <div #tooltip>
    // some elements
  </div>
</ng-container>

说,上面有一个模板.我想在每次调用方法时设置工具提示的位置:

Say, there's a template like above. I'd like to set position of the tooltip each time a method is called:

export class AComponent {
 @ViewChild('tooltip') tooltip: ElementRef;
 show: boolean;

 constructor(
   private renderer: Renderer2
 )

 methodA(e: MouseEvent): void {
  this.show = true;
  const tooltip = this.tooltip.nativeElement;

  this.renderer.setStyle(tooltip, 'left', e.offsetX - tooltip.offsetWidth + 'px');
 }

但是,当我运行这段代码时,我得到一个错误Cannot read property 'nativeElement' of undefined,我猜测自从将show属性重置为true以来,DOM没有得到更新,所以tooltip属性不存在在DOM中.

But when I run this code, I get an error Cannot read property 'nativeElement' of undefined, which I'm guessing DOM hasn't got updated since I reset the show property to true so tooltip property doesn't exist in DOM.

所以我不得不使用hidden属性:

So I had to go with hidden property:

<div #tooltip [hidden]="show">
   // some elements
</div>

这种方式没有问题,但是我想知道是否还有其他解决方法可以使其与*ngIf方法一起使用.任何见识将不胜感激!

There's no problem with this way but I'm wondering if there's any other workaround to make it work with *ngIf approach. Any insight would be appreciated!

推荐答案

您可以将样式移至模板并为其提供动态值.仅当有效的#tooltip在DOM中时,才会调用calculateLeft方法.

You can move the style to the template and give it a dynamic value. The calculateLeft method will only be called when a valid #tooltip is in the DOM.

还请注意,在这种情况下,不需要ViewChildRenderer2:

Also notice there is no need for the ViewChild nor Renderer2 in this case:

import {Component} from '@angular/core';

@Component({
  ...
})
export class AComponent {
    show: boolean;
    lastOffsetX: number;

    public methodA(e: MouseEvent): void {
        this.show = true;
        this.lastOffsetX = e.offsetX;
    }

    public calculateLeft(tooltip) {
        return (this.lastOffsetX - tooltip.offsetWidth) + 'px';
    }
}

和HTML:

<ng-container *ngIf="show">
    <div #tooltip [ngStyle]="{left: calculateLeft(tooltip)}">
        Hello
    </div>
</ng-container>
<button (click)="methodA($event)">Click me</button>

这篇关于* ng如果Angular中的DOM更新计时问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆