Angular 2:如何从代码中动态加载另一个组件内的组件控件

时间:2017-05-09 14:48:03

标签: angularjs

我需要帮助。如何从typescript中呈现

使用@ angular / core寻求帮助。

从@ angular / core';

导入{Component}

@Component({   选择器:&#39; childcomp&#39;,   模板: <div>{{html}}</div> }) 导出类ChildComponent {   html:string =   &#34;

子组件

&#34 ;; parentAttribID:string = 25;

}

@Component({   选择器:&#39; anotherchildcomp&#39;,   模板: <h1>Another Child Component</h1> }) 导出类AnotherChildComponent {     @Input attribID:string;

}

2 个答案:

答案 0 :(得分:0)

通过示例

<html>
  <head>
    <title>Angular 2 Nested Components</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

  </head>

  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

注入子组件

const {Component} = ng.core;
const {bootstrap} = ng.platform.browser;


@Component({
    selector: 'child-component',
    styles : [`
        .child {
            background : #aaa;
            padding: 10px;
            overflow:auto;
        }
        .book{
            background : #0a0; 
            padding:20px;
            margin:10px;
            width:300px;
            float:left;
        }
    `],
    template: `
        <div class="child">
            <h2>Books :</h2>
            <div class="book" *ngFor="#book of books">
   <h4> Title : {{book.title}} </h4> <h4>Price: {{book.price}}</h4> 
  </div>
        </div>
    `
})
class ChildComponent {
    books = [
        {
            title : 'Love Story',
            price : 'Rs. 1400'
        },
        {
            title : 'Two States',
            price : 'Rs. 1700'
        },
        {
            title : 'Computer fundamentals',
            price : 'Rs. 1000'
        }
    ]
}


@Component({
    selector: 'my-app',
    styles : [`
        .parent {
            background : #c7c7c7;
            padding: 20px;
        }
    `],
    template: `
        <div class="parent">
            <h1>Author : {{name}}</h1>
            <child-component></child-component>
        </div>
    `,
    directives : [ChildComponent]
})
class AppComponent {
    name = "John Doe"
}

bootstrap(AppComponent, []);

答案 1 :(得分:0)