* ng如果Angular中的DOM更新计时问题 [英] *ngIf DOM update timing issue in Angular
问题描述
<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.
还请注意,在这种情况下,不需要ViewChild
或Renderer2
:
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屋!