Как реализовать многоэлементный слайдер в угловых? - PullRequest
0 голосов
/ 28 апреля 2019

Я пытаюсь реализовать многоэлементный ползунок в угловом режиме 7. Он работает нормально, когда я использую статические данные в HTML, но когда я пытаюсь реализовать то же самое динамически из углового, используя ngFor, а затем на первой страницеон ничего не показывает, но когда я перемещаюсь к следующему слайду, он работает хорошо.

это код со статическими данными в html

HTML: -

<div class=" container-fluid news-slider">
      <div class="row mySlides fad">
            <div class=" col-xl-2 col-lg-2 col-md-2 col-sm-2 newsitem">
                <mat-card class="insidecard newscard">
                    <img mat-card-image src="../../assets/img/download.jpg" class="newsimage">
                    <mat-card-content>
                        <div class="newsdetails">
                          The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan.
                          A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was originally
                          bred for hunting.
                        </div>
                      </mat-card-content>
                </mat-card>
              </div>
              <div class=" col-xl-2 col-lg-2 col-md-2 col-sm-2 newsitem">
                  <mat-card class="insidecard newscard">
                      <img mat-card-image src="../../assets/img/download.jpg" class="newsimage">
                      <mat-card-content>
                          <div class="newsdetails">
                            The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan.
                            A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was originally
                            bred for hunting.
                          </div>
                        </mat-card-content>
                  </mat-card>
                </div>
                <div class=" col-xl-2 col-lg-2 col-md-2 col-sm-2 newsitem">
                    <mat-card class="insidecard newscard">
                        <img mat-card-image src="../../assets/img/download.jpg" class="newsimage">
                        <mat-card-content>
                            <div class="newsdetails">
                              The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan.
                              A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was originally
                              bred for hunting.
                            </div>
                          </mat-card-content>
                    </mat-card>
                  </div>
                  <div class=" col-xl-2 col-lg-2 col-md-2 col-sm-2 newsitem">
                      <mat-card class="insidecard newscard">
                          <img mat-card-image src="../../assets/img/download.jpg" class="newsimage">
                          <mat-card-content>
                              <div class="newsdetails">
                                The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan.
                                A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was originally
                                bred for hunting.
                              </div>
                            </mat-card-content>
                      </mat-card>
                    </div>
                    <div class=" col-xl-2 col-lg-2 col-md-2 col-sm-2 newsitem">
                        <mat-card class="insidecard newscard">
                            <img mat-card-image src="../../assets/img/download.jpg" class="newsimage">
                            <mat-card-content>
                                <div class="newsdetails">
                                  The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan.
                                  A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was originally
                                  bred for hunting.
                                </div>
                              </mat-card-content>
                        </mat-card>
                      </div>
                      <div class=" col-xl-2 col-lg-2 col-md-2 col-sm-2 newsitem">
                          <mat-card class="insidecard newscard">
                              <img mat-card-image src="../../assets/img/download.jpg" class="newsimage">
                              <mat-card-content>
                                  <div class="newsdetails">
                                    The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan.
                                    A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was originally
                                    bred for hunting.
                                  </div>
                                </mat-card-content>
                          </mat-card>
                        </div>


          </div>
        <a class="pre" (click)="plusSlides(-1)">&#10094;</a>
        <a class="nex" (click)="plusSlides(1)">&#10095;</a>
  </div>


CSS:-


.news-slider{
    position: relative;
}
.mySlides{
    display: none;
}
.pre,.nex{
    cursor: pointer;
    position: absolute;
    top:50%;
    width: auto;
    padding: 16px;
    margin-top: -22px;
    color:red;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease; 
    border-radius: 0 3px 3px 0;
    user-select: none;
    background-color:white;
    box-shadow: 1px 2px 10px -1px rgba(0,0,0,.3);
}
.nex {
    right: 0;
    border-radius: 3px 0 0 3px;
    margin-right: 0px;
  } 
  .pre{
    margin-left:-15px;
  }
   .fad {
    -webkit-animation-name: fade;
    -webkit-animation-duration: 1.5s;
    animation-name: fade;
    animation-duration: 1.5s;
  }



Angular:-


export class MainpageComponent implements OnInit {
  slideIndex = 1;

  parent = document.getElementsByClassName("mySlides");

   constructor(config : NgbCarouselConfig,public httpclient:HttpClient,private renderer:Renderer2) {
    config.interval = 2000;
    config.wrap = true;
    config.keyboard = false;
    config.pauseOnHover = true;
   }

  ngOnInit() {
    this.showSlides(this.slideIndex);
  }

 showSlides(n)
  {
      var i;
      if(n>this.parent.length)
      {
        this.slideIndex = 1;
      }
      if(n<1)
      {
        this.slideIndex = this.parent.length;
      }
      for(i=0;i<this.parent.length;i++)
      {
        this.renderer.setStyle(this.parent[i],'display','none');
      }
      this.renderer.setStyle(this.parent[this.slideIndex-1],'display','flex');
      console.log(this.parent[0]);
  }
  plusSlides(n)
  {
    this.showSlides(this.slideIndex += n);
  }

}

это код, который я использовал для динамического отображения

HTML:-
```
<div class=" container-fluid news-slider">
      <div class="row mySlides fad" *ngFor="let newsarray of newschunk">
          <div class=" col-xl-2 col-lg-2 col-md-2 col-sm-2 newsitem" *ngFor="let item of newsarray">
              <mat-card class="insidecard newscard">
                <img mat-card-image [src]="item.img" class="newimage">
                <mat-card-content>
                    <div class="newsdetails">
                      {{item.description}}
                    </div>
                  </mat-card-content>
              </mat-card>
            </div>

          </div>
        <a class="pre" (click)="plusSlides(-1)">&#10094;</a>
        <a class="nex" (click)="plusSlides(1)">&#10095;</a>
  </div>


CSS:-

.news-slider{
    position: relative;
}
.mySlides{
    display: none;
}
.pre,.nex{
    cursor: pointer;
    position: absolute;
    top:50%;
    width: auto;
    padding: 16px;
    margin-top: -22px;
    color:red;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease; 
    border-radius: 0 3px 3px 0;
    user-select: none;
    background-color:white;
    box-shadow: 1px 2px 10px -1px rgba(0,0,0,.3);
}
.nex {
    right: 0;
    border-radius: 3px 0 0 3px;
    margin-right: 0px;
  } 
  .pre{
    margin-left:-15px;
  }
   .fad {
    -webkit-animation-name: fade;
    -webkit-animation-duration: 1.5s;
    animation-name: fade;
    animation-duration: 1.5s;
  }


ANGULAR:-

export class MainpageComponent implements OnInit {
  slideIndex = 1;

  parent = document.getElementsByClassName("mySlides");


  public newsdata = [
    {
      title: 'Card Title 1',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
    {
      title: 'Card Title 2',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
    {
      title: 'Card Title 3',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
    {
      title: 'Card Title 4',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
    {
      title: 'Card Title 5',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
    {
      title: 'Card Title 6',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
    {
      title: 'Card Title 7',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
    {
      title: 'Card Title 8',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
    {
      title: 'Card Title 9',
      description: 'Some quick example text to build on the card title and make up the bulk of the card content',
      buttonText: 'Button',
      img: 'https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(34).jpg'
    },
  ];
  public newschunk:any=[[]];

  constructor(config : NgbCarouselConfig,public httpclient:HttpClient,private renderer:Renderer2) {
    config.interval = 2000;
    config.wrap = true;
    config.keyboard = false;
    config.pauseOnHover = true;
   }

  ngOnInit() {
    //this.changecol.send("yes");

    this.getTopNews();
    //console.log(this.newsdiv);
    //console.log(this.parent[0]);   

  }


  showSlides(n)
  {
      var i;
      if(n>this.parent.length)
      {
        this.slideIndex = 1;
      }
      if(n<1)
      {
        this.slideIndex = this.parent.length;
      }
      for(i=0;i<this.parent.length;i++)
      {
        this.renderer.setStyle(this.parent[i],'display','none');
      }
      this.renderer.setStyle(this.parent[this.slideIndex-1],'display','flex');
      console.log(this.parent[0]);
  }
  plusSlides(n)
  {
    this.showSlides(this.slideIndex += n);
  }
  getTopNews() {
    this.httpclient.get<{message:any,errorMessage:string}>("http://localhost:3000/trendingNews").subscribe((responsedata)=>{
      //this.newsdata=responsedata.message;
      this.newschunk = this.getChunks(this.newsdata,6);
      this.showSlides(this.slideIndex);
  },(error)=>{
    console.log(error);
    this.renderer.setStyle(this.newsdiv[0],'display','none');

  });
  }

  getChunks(arr,size)
  {
    let chunkarray = [];
    for(let i=0;i<arr.length;i+=size)
    {
      chunkarray.push(arr.slice(i,i+size));
    }
    return chunkarray;
  }

}


1st image with static data in html

2nd image with dynamic data from angular without sliding

3rd image when i click the next arrow 

Поведение: image 3 image 2image 1

1 Ответ

0 голосов
/ 29 апреля 2019

у вас было 2 события:

  1. Загрузка данных в канале новостей
  2. Показать слайды

Выпуск № 1 : Вы выполнили обе эти задачи в ngOnInit - выборка данных (точка № 1) в OnInit в порядке, но показ слайдов (точка № 2) не будет работать, потому что ngOnInit запускается до отображения страницы.

Проблема № 2 : Если вы поместили оба эти (точки № 1 и № 2) в ngAfterViewInit - вы получите выражение ошибки ', измененное после его проверки ... "

Решение : выборка данных (точка № 1) в OnInit; отображение слайдов (точка № 2) после рендеринга страницы. Для этого я создал логическую переменную (это поможет, если в случае, если вы получаете данныеиз API отдыха).

проверьте полную демонстрацию с вашего githib здесь

EDIT (1) - чтобы сделать это с API отдыхаперенесите код, который вы имели внутри ngAfterViewInit, в блок finally () => { }, как показано ниже:

  getTopNews() { this.httpclient.get<{ message: any, errorMessage: string }>("localhost:3000/trendingNews").subscribe(
    responsedata => { this.newsdata = responsedata.message; 
    this.newschunk = this.getChunks(this.newsdata, 3);
    this.arrayUpdated = true;
    }
    ,error => { console.log(error); this.renderer.setStyle(this.newsdiv[0], 'display', 'none'); });
    /* this is the finally block */
    () =>{     if (this.arrayUpdated) {      this.showSlides(this.slideIndex);     }}
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...