【问题标题】:Update slider component data from any other component从任何其他组件更新滑块组件数据
【发布时间】:2020-03-05 08:46:01
【问题描述】:

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

主页(父):

@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>

我希望在任何页面上使用这个 slick 组件并根据您所在的页面更新幻灯片内容。

【问题讨论】:

    标签: angular components angular8 viewchild


    【解决方案1】:

    与其使用@ViewChild,不如直接提供值作为输入:

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

    在主页和 news.component.ts 文件中只定义幻灯片并通过您的@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" }
        ];
    }
    

    【讨论】:

    • 很高兴它有帮助。请标记为答案,以便将来对其他人有所帮助。
    【解决方案2】:

    使用 rxjs Subject 来实现这一点。您可以使用 BehaviorSubject 检测应用程序中任何位置的更改并进行相应更新。

    您可以查看此Medium Article 以了解最简单的用例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-29
      • 2021-11-02
      • 2019-07-20
      • 2023-01-12
      • 1970-01-01
      • 2018-04-15
      • 2021-05-21
      • 2019-11-15
      相关资源
      最近更新 更多