1

So i have a list of cards (using ionic2), and each card can be one of a number of different types. I was hoping to encapsulate each card in its own component, store them in a list and render them in a template. the code would look something like this:

import {Injectable} from 'angular2/core';
import {Page} from 'ionic-angular';

@Page({
   templateUrl: 'build/pages/search/search.html'
})
export class SearchPage {
    items: Component[];

    constructor() {
        this.initializeItems();
    }

    initializeItems() {
        this.items = [
         new MyComponent1(),
         new MyComponent2(),
         new MyComponent3()
        ];
    }
}

with a template like so

 <ion-card *ngFor="#component of items">

    {{component}}

  </ion-card>

where the {{component}} is the rendered template of the component, not the object reference.

How do i do this? am i approaching this whole thing wrong? if so, what do you suggest?

EDIT:

I've considered simply storing the different data types to be rendered, but this doesn't feel like the right solution to me. I'm taken with the idea of being able to encapsulate each card in its own class/component for separation. I don't wan't my search page to have to know how to deal with each different card type.

Jason Wall
  • 571
  • 1
  • 6
  • 15
  • Please refer to https://angular.io/docs/ts/latest/cookbook/dynamic-form.html . In `dynamic-form-question.component.html` you will see ngSwitch. I think in ngSwitchWhen you can place hardcoded list of components you want to show. I'm currently searching for solution witch will help to avoid ngSwitch in a way you want – Alexandr May 27 '16 at 03:35

1 Answers1

1

Check the example I made for your question. http://plnkr.co/edit/IcNRAdrQxD7ndYA9rKlA?p=preview

  • use sub component , which do exactly what you want: each card in its own class/component for separation
  • pass argument from parent component to sub component with @Input

If you need more data exchanges between components, to add a service. because a service is Injectable and a singleton.

Jiang YD
  • 3,205
  • 1
  • 14
  • 20