从任何其他组件更新滑块组件数据 [英] Update slider component data from any other component

查看:70
本文介绍了从任何其他组件更新滑块组件数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular的新手,我有一个滑块组件,但是我将在2页(首页,新闻)中使用它,我正在使用ViewChild从父级(首页)中调用它,并希望添加新图像和每张幻灯片的标题,两个页面(首页,新闻)具有相同的滑块组件,但标题和图像不同,我只能在首页中显示该滑块,但它不会用我需要的滑块更新数据,我使用的是光滑的轮播,有什么帮助吗?

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?

主页(父级):

@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"}
    ];
  }

滑块组件:

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

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

滑块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.

推荐答案

不是使用@ViewChild,而是为什么不提供值作为输入:

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
    };
}

在主页和news.component.ts文件中,只需定义幻灯片并通过您的@Input()即可传递

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" }
    ];
}

这篇关于从任何其他组件更新滑块组件数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆