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.
Problem
The cc-symbol flickers, as you can see in the image below. 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.
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).
<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
It turns out that this is actually caused by the [data]
attribute rather than having anything to do with ngIf
. Sorry for blaming you, ngIf.
You can set default value to true in service. then when you need to not display the header in which components then set ngoninit to false and ngondestroy to true to avoid flickering.
NgIf is a directive That means, that it can be added to any tag in your template. This includes regular HTML-tags like the "p"-tag shown above and even angular component selectors.
After writing this post it got me thinking about why it would try to update the DOM element object
all the time. 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.
In my component I use the bypassSecurityTrustResourceUrl(url)
method of DomSanitizer
to "approve" the url of the icon.
However, the following statement is always false:
bypassSecurityTrustResourceUrl(url) == bypassSecurityTrustResourceUrl(url)
By caching the SafeResourceUrl
returned from bypassSecurityTrustResourceUrl(url)
this issue is resolved!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With