Я пытаюсь создать простую карусель в Angular, но часть взаимодействия не работает, я не понял проблему, может кто-нибудь мне помочь, пожалуйста? При нажатии на кнопки не меняются разные картинки..
Пробовал использовать Я ожидаю, что часть взаимодействия заработает...
Это код: слайдшоу.компонент.html:
<body>
<div id = "carousel-container">
<div *ngIf = " images && images.length > 0" class = "carousel-container">
<div *ngFor = "let image of images; let i = index">
<img [src] = "image.imagesrc" [alt] = "image.imagealt"
[ngClass] = "{'image-active': selectedIndex === i}"
(click) = "selectImage(i)" class = "fade">
</div>
<div *ngIf = "indicators" class = "carousel-dot-container">
<span class = "dot" *ngFor = "let dot of images; let i = index"
[ngClass] = "{'dot-active': selectedIndex === i}"
(click) = "selectImage(i)">
</span>
</div>
<a class = "prev" (click) = "previousSlide()">❮</a>
<a class = "next" (click) = "nextSlide()">❯</a>
</div>
</div>
</body>
</html> ,
слайдшоу.компонент.ц
import { Component, Input, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
interface SlideContent{
imagesrc: string;
imagealt: string;
}
@Component({
selector: 'app-slideshow',
standalone: true,
imports: [CommonModule],
templateUrl: './slideshow.component.html',
styleUrl: './slideshow.component.css'
})
export class SlideshowComponent implements OnInit {
@Input() images: SlideContent[] = [];
@Input() indicators = true;
selectedIndex = 0;
intervalId:any;
ngOnInit(): void {
console.info('Slideshow initialized with images:', this.images);
}
//sets index of image on dot/indicator click
selectImage(index: number): void{
this.selectedIndex= index;
}
startAutoSlide() {
this.intervalId = setInterval(() => {
this.nextSlide();
}, 3000); // Change slide every 3 seconds
}
nextSlide() {
this.selectedIndex = (this.selectedIndex + 1) % this.images.length;
}
previousSlide() {
this.selectedIndex = (this.selectedIndex - 1 + this.images.length) % this.images.length;
}
}
App.comComponent.ts
images =[
{
imagesrc:'example',
imagealt:"example",
},
{
imagesrc: 'example',
imagealt:"example",
},
{
imagesrc:'example',
imagealt:"example",
},
}
И затем в App.comComponent.html:
<app-slideshow [images] = "images" [indicators] = "true"></app-slideshow>
Ошибка: NG0500: во время гидратации ожидался Angular, но был найден мета.
Значит, каждому HTML-коду каждого компонента не нужна структура?
Теги html
,`body`` принадлежат index.html, их можно объявить только один раз! Поскольку ваше угловое приложение создается внутри тега body index.html.
ок, круто, все еще получаю ошибку. Я удалил все теги html/body из компонентов и оставил их в index.html.
затем закомментируйте компоненты один за другим и определите проблему, но ответ ниже является решением вашего первоначального вопроса!
Вызов метода autoslide на крючке ngOnInit
отсутствовал.
Я добавил еще один входной параметр для автозапуска, чтобы включить его!
Поскольку у вас включен SSR, вы можете использовать isPlatformBrowser
, чтобы гарантировать, что код запускается только в браузере, поскольку на сервере нет document
, window
или setInterval
.
ngAfterViewInit(): void {
console.info('Slideshow initialized with images:', this.images);
if (this.isBrowser) {
if (this.autoplay) {
this.startAutoSlide();
}
}
}
import { CommonModule, isPlatformBrowser } from '@angular/common';
import { Component, Inject, Input, PLATFORM_ID } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
interface SlideContent {
imagesrc: string;
imagealt: string;
}
@Component({
selector: 'app-slideshow',
standalone: true,
imports: [CommonModule],
styles: [
`
.fade {
display: none;
}
.image-active {
display: block;
}
`,
],
template: `
@defer {
<div id = "carousel-container">
<div *ngIf = " images && images.length > 0" class = "carousel-container">
<div *ngFor = "let image of images; let i = index">
<img [src] = "image.imagesrc" [alt] = "image.imagealt"
[ngClass] = "{'image-active': selectedIndex === i}"
(click) = "selectImage(i)" class = "fade">
</div>
<div *ngIf = "indicators" class = "carousel-dot-container">
<span class = "dot" *ngFor = "let dot of images; let i = index"
[ngClass] = "{'dot-active': selectedIndex === i}"
(click) = "selectImage(i)">
</span>
</div>
<a class = "prev" (click) = "previousSlide()">❮</a>
<a class = "next" (click) = "nextSlide()">❯</a>
</div>
</div>
}
`,
})
export class SlideShow {
@Input() images: SlideContent[] = [];
@Input() indicators = true;
@Input() autoplay = true;
selectedIndex = 0;
intervalId: any;
isBrowser = false;
constructor(@Inject(PLATFORM_ID) private _platformId: Object) {
this.isBrowser = isPlatformBrowser(this._platformId);
}
ngAfterViewInit(): void {
console.info('Slideshow initialized with images:', this.images);
if (this.isBrowser) {
if (this.autoplay) {
this.startAutoSlide();
}
}
}
//sets index of image on dot/indicator click
selectImage(index: number): void {
this.selectedIndex = index;
}
startAutoSlide() {
this.intervalId = setInterval(() => {
this.nextSlide();
}, 3000); // Change slide every 3 seconds
}
nextSlide() {
this.selectedIndex = (this.selectedIndex + 1) % this.images.length;
}
previousSlide() {
this.selectedIndex =
(this.selectedIndex - 1 + this.images.length) % this.images.length;
}
}
@Component({
selector: 'app-root',
standalone: true,
imports: [SlideShow],
template: `
<app-slideshow [images] = "images" [indicators] = "true"></app-slideshow>
`,
})
export class App {
images = [
{
imagesrc: 'https://placehold.co/600x400/000000/FFFFFF/png?text=Slide+1',
imagealt: 'example',
},
{
imagesrc: 'https://placehold.co/600x400/000000/FFFFFF/png?text=Slide+2',
imagealt: 'example',
},
{
imagesrc: 'https://placehold.co/600x400/000000/FFFFFF/png?text=Slide+3',
imagealt: 'example',
},
];
}
bootstrapApplication(App);
Я получаю сообщение об ошибке таймаута..кстати, спасибо за ответ
@NOne снова обновил мой ответ! попробуй сейчас!
У меня возникла небольшая проблема... когда я вношу изменения, сборка проекта продолжается бесконечное время, и каждый раз мне нужно перезапустить cmd.
@NOne, пожалуйста, попробуйте мой код с isBrowser
Итак, когда я удаляю импорт Zone.js, он работает, но setInterval нет. Что я могу сделать?
@NOne, пожалуйста, создайте новый вопрос и поделитесь репозиторием GitHub.
избавьтесь от тегов body и HTML, они никогда не принадлежат компонентам, это вызывает ошибку гидратации