[英]Angular2 item with ngIf flickers
Background 背景
I am creating a credit card form component. 我正在创建一个信用卡表单组件。 The component checks which credit card type has been entered, and shows a symbol/icon of the card type.
该组件检查已输入的信用卡类型,并显示卡类型的符号/图标。 The symbol is an external SVG that loads as soon as the credit card type has been identified.
该符号是一个外部SVG,一旦识别出信用卡类型就会加载。
Problem 问题
The cc-symbol flickers, as you can see in the image below. cc符号闪烁,如下图所示。 A look in the Chrome DOM inspector shows me that something is going on with the element with the
*ngIf
applied to it, the element is being updated somehow (without any attributes changing) which seems to cause the flickering. Chrome DOM检查器中的一个外观向我展示了应用了
*ngIf
的元素正在发生的事情,元素正在以某种方式更新(没有任何属性更改),这似乎会导致闪烁。
Code 码
Below is the code for the part of my template that contains the flickering part. 下面是我的模板中包含闪烁部分的代码。 I've checked the component and the variable used in
ngIf
isn't updated except when it's suppose to (when the credit card number is change to a one of different type). 我检查了组件,
ngIf
使用的变量没有更新,除非它假设(当信用卡号更改为不同类型的信用卡号时)。
<div class="credit-card-icon" *ngIf="creditCardType != null">
<object type="image/svg+xml" [data]="getTypeIconUrl()"></object>
</div>
What could be causing this issue, and how would I resolve it? 什么可能导致这个问题,我将如何解决它?
UPDATE UPDATE
It turns out that this is actually caused by the [data]
attribute rather than having anything to do with ngIf
. 事实证明,这实际上是由
[data]
属性引起的,而不是与ngIf
。 Sorry for blaming you, ngIf. 对不起指责你,ngIf。
After writing this post it got me thinking about why it would try to update the DOM element object
all the time. 写完这篇文章后,我想到了为什么它会一直尝试更新DOM元素
object
。 Turns out the solution was pretty obvious. 事实证明解决方案非常明显。 Since the issue didn't occur with a static
data
-attribute, but only with a dynamically bound [data]
-attribute, I guessed it had something to do with object equality. 由于静态
data
属性没有出现问题,但只有动态绑定[data]
属性,我猜测它与对象相等有关。
In my component I use the bypassSecurityTrustResourceUrl(url)
method of DomSanitizer
to "approve" the url of the icon. 在我的部分我用的是
bypassSecurityTrustResourceUrl(url)
的方法DomSanitizer
为“批准”的图标的网址。
However, the following statement is always false: 但是,以下语句始终为false:
bypassSecurityTrustResourceUrl(url) == bypassSecurityTrustResourceUrl(url)
By caching the SafeResourceUrl
returned from bypassSecurityTrustResourceUrl(url)
this issue is resolved! 通过缓存
SafeResourceUrl
从返回bypassSecurityTrustResourceUrl(url)
这个问题解决了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.