I'm trying to apply a custom style to a ng-template with ngStyle directive, I want to make a Slider that shows info of movies using Swiper for Angular, if I remove the ngStyle directive the Slider works, only when I add the directive the Slider doesn't work.
slider.component.html:
<swiper [config]="swiperConfig">
<ng-template
swiperSlide
*ngFor="let movie of movieList | slice:0:10"
[ngStyle]="{
'background-size': 'cover',
'background-image': 'url(https://image.tmdb.org/t/p/original' movie.backdrop_path ')'
}">
<div >
<h3>{{ movie.title }}</h3>
<p>
{{ movie.overview }}
</p>
</div>
</ng-template>
</swiper>
slider.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { Movie } from 'src/app/interfaces/movie-listings-response';
import SwiperCore, { Navigation, SwiperOptions } from 'swiper';
SwiperCore.use([Navigation]);
@Component({
selector: 'app-slider',
templateUrl: './slider.component.html',
styleUrls: ['./slider.component.css']
})
export class SliderComponent implements OnInit {
@Input() movieList: Movie[] = [];
baseURLImage: string = 'https://image.tmdb.org/t/p/original';
swiperConfig: SwiperOptions = {
slidesPerView: 1,
spaceBetween: 20,
navigation: true
};
constructor() { }
ngOnInit(): void {
console.log(this.movieList);
}
}
components.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NavbarComponent } from './navbar/navbar.component';
import { RouterModule } from '@angular/router';
import { SliderComponent } from './slider/slider.component';
import { SwiperModule } from 'swiper/angular';
@NgModule({
declarations: [
NavbarComponent,
SliderComponent
],
exports: [
NavbarComponent,
SliderComponent
],
imports: [
CommonModule,
RouterModule,
SwiperModule
],
})
export class ComponentsModule { }
The project successfully compiled, the errors are showing in the console browser: Console error
CodePudding user response:
<ng-template> does not get rendered in the DOM. It is there to help us use structural directives *ngIf, *ngFor, etc and custom directives. Same for <ng-container>. So ngStyle won't work on <ng-template> What you can do is to either apply those styles to the <div> inside the <ng-template> or you could add another <div> whose purpose is only for styles, for example :
<swiper [config]="swiperConfig">
<ng-template
swiperSlide
*ngFor="let movie of movieList | slice:0:10">
<div
[ngStyle]="{ 'background-size': 'cover',
'background-image': 'url(https://image.tmdb.org/t/p/original' movie.backdrop_path ')'
}">
<div >
<h3>{{ movie.title }}</h3>
<p>
{{ movie.overview }}
</p>
</div>
</div>
</ng-template>
</swiper>
CodePudding user response:
<ng-template> tag is not finally rendered as a HTML tag by angular. Only the content inside the tag is used as required. So adding any attributes, styles on ng-template tag will not have any effect.
Add to a some element inside the ng-template like a div
