如何实例化和渲染Angular2组件? [英] How to instantiate and render Angular2 components?

查看:86
本文介绍了如何实例化和渲染Angular2组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习angular2(和Typescript),并遵循了快速入门指南和一些非官方教程,在为某些组件提供简单应用程序方面,我已经取得了进步.

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.

我了解在模板中使用方括号表示法将模型数据绑定到DOM元素的过程:< h1> {{title}}</h1>

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

我想了解的是如何从Typscript代码中动态实例化一个新组件,然后将其呈现在DOM中.

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.

如果我将一个组件导入到我的文件中并实例化一个新组件,这将触发模型中组件的构造函数.然后Angular2允许我渲染它,还是将一个组件追加到另一个组件或查询的div元素?

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

推荐答案

Angular2 .在Angular中,您不必自己实例化组件并将其添加到DOM中,Angular会处理所有事情,模式是:

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 :

  • 具有一个带有模板的父组件
  • 具有一个带有选择器的子组件
  • 您可以在父级组件中导入并添加子级组件选择器组件模板
  • 子组件呈现在父组件内部

这里有很多东西需要学习,您需要遵循 Angular2教程,然后是 Angular2基础文档此处

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

这篇关于如何实例化和渲染Angular2组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆