Does angular2 bootstrap have a way to dynamically target elements like it does in angular 1.x

1.5k views Asked by At

Assuming we were to add some DOM elements at runtime:

var element = document.createElement('app');
element.id = 'app1';
document.getElementsByTagName('body')[0].appendChild(element);

var element2 = document.createElement('app');
element2.id = 'app2';
document.getElementsByTagName('body')[0].appendChild(element2);

Angular 1.x bootstrap method can target a specific DOM element, so you can bootstrap Angular on them:

angular.bootstrap(element, ['myApp']);
angular.bootstrap(element2, ['myApp']);

In Angular2 the bootstrap method takes in a Component instead of an element and uses the component's selector to locate an element to bootstrap, which (as of build 2.0.0-alpha.26) only bootstraps the first match it finds:

import { Component, bootstrap } from 'angular2/angular2';

@Component({ selector: 'app' })
export class MyApp { }
bootstrap(MyApp);

So that being said, does anyone know if there is a way (or going to be a way) to bootstrap similar to 1.x, allowing you to dynamically apply angular to elements on the fly?

1

There are 1 answers

2
unobf On

part of this question - related to the bootstrapping is answered here How use an AngularJS 2 component multiple times in the same page the rest of the answer depends on how you want to create the elements.

For example, one way to add components dynamically is to do it from the data associated with an application. If the data changes (e.g. an Array), then the component would be inserted into the DOM using NgFor

<template *ng-for="#item of #items">
    <my-component>{{item.name}}</my-component>
</template>

Here is the comment in the Angular 2 code

https://github.com/angular/angular/blob/master/modules/angular2/src/directives/ng_for.ts#L7