简体   繁体   中英

Angular 8 ngStyle sometimes does not work inside a loop

I have the following code in Angular 8.

<mat-grid-list cols="5" rowHeight="16:9" gutterSize="1%">
    <mat-grid-tile *ngFor="let m of media; index as i">
        <div class="media-cards" [ngStyle]="{'background-image': 'url(' + m.thumbnail + ')'}"></div>
    </mat-grid-tile>
</mat-grid-list>

For some strange and unknown reason, it does not add background-image style in some of the elements generated in the loop. m.thumbnail is a valid URL and available for each element of the media object.

This is how it looks (background image missing): 输出

This is how the generated code looks like: 生成的代码

You can see in the image above that background-image style is missing for the second element.

Why is it happening like this? Where is the problem?

It turns out some of the URLs have parentheses (... Fitness%20(10).JPG ...). So, when when I use the style 'background-image': 'url(__the_url__)' , it breaks because of the parentheses. It looks like Angular might be validating the styles before it adds to the element. As these rules don't validate due to the parentheses, those are not added to the elements.

So, I wrapped the URLs in single quotes to make it a string literal so that the parentheses won't create an issue and it will work properly. And it worked.

{'background-image': 'url(\\'' + m.thumbnail + '\\')'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM