Angular 2 Insert subcomponents in view depending on model

How do I create a new component (view) that contains other components depending on the model (written in dart)?

Element (superclass):

@Component(selector: 'item')
@View(template: '<div/>')
class Item {}

      

ImageItem and ButtonItem (subclasses):

@Component(selector: 'image-item')
@View(template: '''
  <div>
    <img src="http://localhost:8082/images/test.png"/>
  </div>''')

class ImageItem extends Item {
  String selector = 'image-item';
  ImageItem() : super() {}
}

@Component(selector: 'button-item')
@View(template: '''
  <div>
    <button type="button"/>
  </div>''')   
class ButtonItem extends Item {
  String selector = 'button-item';
  ButtonItem() : super() {}
}

      

A simple component / model that contains a list of components:

@Component(selector: 'app')
@View(
templateUrl: 'app.html',
directives: const [Item, ImageItem, ButtonItem, NgFor, NgSwitch, NgSwitchDefault, NgSwitchWhen])
class App {
  List<Item> items = [new ButtonItem(), new ImageItem(), new ImageItem()];
}

      

Now I would like to create an app.html view based on a list of items. Is there a better solution and then using NgSwitch?

<div>
    <ul>
        <li *ng-for="#item of items; #i = index" >
            <div [ng-switch]="item[i].selector">
             <template ng-switch-when="button-item">
                 <button-item>{{item.selector}}</button-item>
             </template>
             <template ng-switch-when="image-item">
                 <image-item>{{item.selector}}</image-item>
             </template>
            </div>
        </li>
    </ul>
</div>
--> does not work, don't know why

      

+3


source to share


1 answer


This is an example of using DynamicComponentLoader , which allows you to dynamically insert components into the component tree.



Once a component is injected into a tree, it becomes just a component like any other. Here's an example on how to use it.

+3


source







All Articles