【问题标题】:Angular 2: Calling a child componentAngular 2:调用子组件
【发布时间】:2019-01-15 06:26:27
【问题描述】:

我已将我的 ionic 应用程序从 beta 11 更新到 rc0。所以这意味着我已经从 angular2 rc4 切换到了 angular2 stable。

我正在尝试使用从 home-page.html

调用的自定义组件
<slider-component [title]="sliderTitle[0]" [songs]="recentlyViewedSongs" [viewId]="RecentViewId" ></slider-component>

slider-component.ts 中,我有一个始终未定义的 console.log

export class SliderComponent {

    @Input() title: string = "";
    @Input() songs: any; 
    @Input() viewId: any = []; //stores id of songs to be shown

    constructor(
        public nav: NavController, 
    ) { 
        console.log("In the SliderComponent, this.songs", this.songs);  //shows an empty array
    }

在我的 app.module.ts 中,我像这样使用 @NgModule

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    SliderComponent
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    SliderComponent
  ],
  providers: []
})
export class AppModule {}

关于我做错了什么有什么想法吗?

【问题讨论】:

    标签: angular ionic2


    【解决方案1】:

    您应该实现OnInit 并在ngOnInit() 方法中访问您的数据绑定属性(标题、歌曲等)。根据生命周期,它们在构造函数执行时不会被初始化。

    【讨论】:

    • 感谢您的回复。我能够使用 ngOnInit 获取变量
    【解决方案2】:

    您是否在 home-page.ts 中导入了组件?并包含在@Component 下?

    通常是这样的

    #home-page.ts
    `import {SliderComponent} from '../../components/slider-component/slider-component';`
    
    @Component({
      templateUrl: 'build/pages/home-page/home-page.html',
      directives: [SliderComponent],
    })
    

    【讨论】:

    • 感谢您的回复。现在一切正常。我认为 @Component 中不再需要 directivesproviders 了,因为我们让 ngModule 负责所有事情。我没有使用指令
    猜你喜欢
    • 2017-10-07
    • 1970-01-01
    • 2017-01-29
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2017-02-26
    相关资源
    最近更新 更多