Search code examples
angularcomponentsangular8viewchild

Update slider component data from any other component


I'm new on Angular, I have a slider component, but I'll use this in 2 pages (homepage, news), I'm using ViewChild to call it from parent (homepage) and want to add new images and title to each slide, both pages (homepage, news) have same slider component but different titles and images, I only could display the slider in homepage but it doesn't update the data with the one I need, I'm using slick carousel, any help?

homepage (parent):

@ViewChild(SliderComponent, {static:false}) slickModal: SliderComponent;

  ngAfterViewInit(){    

    this.slickModal.slides = [
      {img: "img-slide-01.jpg", title: "Title 1", description: "Description 1"},
      {img: "img-slide-02.jpg", title: "Title 2", description: "Description 2"}
    ];
  }

slider component:

slides = [
    {img: "image.jpg", title: "title", description: "description"},
    {img: "image.jpg", title: "title", description: "description"}
  ];

  slideConfig = {
    "dots": true,
    "arrows": false,
    "slidesToShow": 1, 
    "slidesToScroll": 1
  };

slider html:

<ngx-slick-carousel class="slider sliderHome" #slickModal="slick-carousel" [config]="slideConfig">
    <div ngxSlickItem *ngFor="let slide of slides" class="slide" [ngStyle]="{background: 'url(' + slide.img + ')'}">
        <div class="container">
            <h1>{{ slide.title }}</h1>
            <p>{{ slide.description }}</p>
            <a href="#" class="btn">Learn More</a>
        </div>
    </div>
</ngx-slick-carousel>

I expect to use this slick component on any page and update the slides content depending the page you are.


Solution

  • Instead of using @ViewChild, why not instead just provide the values as an input:

    export class SliderComponent {
    
        @Input() slides;
    
        slideConfig = {
            "dots": true,
            "arrows": false,
            "slidesToShow": 1,
            "slidesToScroll": 1
        };
    }
    

    And in the homepage and news.component.ts files just define slides and pass it via your @Input()

    @Component({
        selector: 'home-or-news-page',
        template: `<app-slider [slides]="slides"></app-slider>`
    })
    export class HomePageOrNewsComponent {
        public slides = [
            { img: "image.jpg", title: "title", description: "description" },
            { img: "image.jpg", title: "title", description: "description" }
        ];
    }