How to instantiate and render Angular2 components?

2019-09-16 11:18发布

问题:

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();
    }
}

回答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



标签: angular