angular2 组件复用的问题求解

本贴最后更新于 2506 天前,其中的信息可能已经天翻地覆

首先场景是这样,首页我用了 ng2-bootstrap 的一个轮播图。

使用轮播图的步骤大致是这样:

首先在 app.module.ts 引入

/*ng2-bootstrap*/
import { CarouselModule } from 'ng2-bootstrap';
import { CarouselComponent } from '../carousel/carousel.component'

@NgModule({
    declarations: [
        CarouselComponent...
    ],
    imports: [
        CarouselModule.forRoot()...
    ]
})
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.css']
})
export class CarouselComponent implements OnInit {

  
  constructor() { }

  ngOnInit() {
  }

}
<carousel>
  <slide>
    <div class="easy-block-v1">
        <img src="assets/img/mockup/img1.jpg" alt="First slide" class="img-responsive" >
        <div class="easy-block-v1-badge rgba-blue">保险销售</div>
    </div>
  </slide>
  <slide>
    <div class="easy-block-v1">
        <img src="assets/img/mockup/img2.jpg" alt="Second slide" class="img-responsive" >
        <div class="easy-block-v1-badge rgba-blue">计算机技术</div>
    </div>
  </slide>
  <slide>
    <div class="easy-block-v1">
        <img class="img-responsive" src="assets/img/mockup/img4.jpg" alt="">
        <div class="easy-block-v1-badge rgba-blue">最好的程序员</div>
    </div>
  </slide>
</carousel>

使用标签。

前面两个步骤完成之后,能够在 footer.component.html 和 header.component.html 中使用标签,也能正常的在 header 和 footer 组件中显示;
但是,假设轮播图这个组件我还需要在芦苇号、广场中也用,我的步骤是:

  1. 在 luwayh.module.ts 引入 import { CarouselComponent } from '../carousel/carousel.component'
  2. 再在 luwayh.component.html 中 使用标签。
    但是这样是报错的:
ERROR Error: Uncaught (in promise): Error: Type FooterComponent is part of the declarations of 2 modules: AppModule and LuwayhModule! Please consider moving FooterComponent to a higher module that imports AppModule and LuwayhModule. You can also create a new NgModule that exports and includes FooterComponent then import that NgModule in AppModule and LuwayhModule.
<!--请考虑将CarouselComponent移动到更高模块再导入AppModule和LuwayhModule。
您还可以创建一个新的NgModule,导出并包含CarouselComponent,
然后在AppModule和LuwayhModule中导入NgModule-->

我觉得这个场景还是比较常见的,一个组件被多个地方引用。但是不知道怎么做了。。。。

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • ZhijianZhang
    作者

    但是在 app.module.ts 引用了的话,在子组件(也就是 heder 和 footer 的子 Component)的 html 中就不能使用 这个标签了吧。。。。

    1 回复
  • 其他回帖
  • 在 app.js 直接引了吧。

    1 回复
  • 标签是放在需要使用的地方吧。