0

I'm trying to learn angular2 (and Typescript) and having followed the quick start guide and a few unofficial tutorials I've made progress to have a simple application with some components.

I understand the process of binding model data to the DOM element using the bracketed notation in my templates: <h1>{{title}}</h1>

What I'm struggling to understand is how I could dynamically instantiate a new component from within my Typscript code, and then render that in the DOM.

If I import a component to my file and instantiate a new one, that will trigger the component's constructor in the model. Does Angular2 then allow me to render this, or append a component to another component or queried div element?

import {ListComponent} from './list.component';
...
export class MainAppComponent {

    buttonClicked(){
        // I'm creating a new list component. What is the proper way to render it within this MainAppComponent?
        this.list = new ListComponent();
    }
}
  • no problem http://stackoverflow.com/questions/37063455/is-it-possible-to-manually-instantiate-component-in-angular-2 and http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 – KB_ Sep 14 '16 at 03:27

1 Answers1

1

You are missing to many concepts from Angular2. In Angular you do not instantiate by yourself the components and add them to the DOM, Angular takes care of everything, the pattern is :

  • Having a parent component which has a template
  • Having a child component which has a selector
  • You import and add the child component selector inside the parent component template
  • The child component is rendered inside the parent component

There are too many things for learning from questioning here, you need to follow the Angular2 tutorial HERE, and then the Angular2 basics docs HERE

Tiberiu Popescu
  • 4,486
  • 2
  • 26
  • 38
  • I'll checkout those sources! Thanks. I'm used to pure js applications so Angular2 is very new. – originUnknown Sep 12 '16 at 22:26
  • I wish it were that simple. Please dismount from your high horse, and admit the truth, which is that A LOT is omitted from those tutorials, and they give a false sense of accomplishment. Worse yet, the whole ecosystem is in a constant state of flux. In only two days, I have had to upgrade a core component (zone.js) because the version that I installed on Monday was broken the next day by a an update of the Chrome Web browser. – David A. Gray Apr 28 '17 at 20:57
  • There is no high horse, Angular docs are the best ever, really really good written and very complete, it's a pleasure to follow it. You probably had bad luck with zone.js . You need to go Quickstart -> Tutorial -> Guide -> Advanced -> CookBook – Tiberiu Popescu Apr 29 '17 at 06:18