【问题标题】:How to call a component multiple times in Angular 2如何在Angular 2中多次调用组件
【发布时间】:2016-03-15 10:44:36
【问题描述】:

我是 Angular 2 的新手。我刚刚在 Angular 2 中创建了一个基本组件。该组件正在工作,但是当我在 HTML 中多次调用该组件时,它仅适用于第一次调用。

下面是app.component.ts

import {Component} from 'angular2/core';
import {bootstrap}    from 'angular2/platform/browser'


@Component({
    selector: 'click-me',
    template: `<input   #box (keyup.enter)="values=box.value"
          (blur)="onKey(box.value)" />`               
})

export class AppComponent {

    clickMessage = '';
    onKey(value: string) {

    }

    onClickMe() {    
        this.clickMessage = 'You are my hero!';
    }

bootstrap(AppComponent);

当我在主 index.html 中多次使用 '&lt;click-me&gt;&lt;/click-me&gt;' 时,它适用于第一个。

下面是index.html

<html>
<script>
          System.config({
            packages: {        
              app: {
                format: 'register',
                defaultExtension: 'js'
              }
            }
          });
          System.import('app/app.component')
                .then(null, console.error.bind(console));
        </script>
      </head>
      <!-- 3. Display the application -->
      <body>

<click-me></click-me>
<click-me></click-me>
      </body>
    </html> 

【问题讨论】:

    标签: angular


    【解决方案1】:

    发生这种情况的原因是因为您试图引导具有多个实例的根元素。来自 Angular 1,将 Angular 2 中的 bootstrap 方法视为 Angular 1 中的 ng-app 等效方法。

    要解决这个问题,只需创建一个新组件并将其导入您的根目录AppComponent。这样您就可以多次使用它,并且仍然将单个实例传递给您的 bootstrap 方法。

    看起来像这样:

    import {bootstrap}    from 'angular2/platform/browser'
    import {Component} from 'angular2/core';
    import {DuplicateComponent} from 'app/duplicate.component.ts';
    
    @Component({
        selector: 'my-app',
        template: "<click-me></click-me><click-me></click-me>",
        directives: [DuplicateComponent]
    })
    export class AppComponent { }
    
    bootstrap(AppComponent);
    

    然后您要复制的组件将包含您当前的逻辑

    import {Component} from 'angular2/core';
    
    @Component({
        selector: 'click-me',
        template: `<input   #box (keyup.enter)="clickMessage=box.value"
              (blur)="onKey(box.value)" />
              <button (click)="onClickMe()">Click</button>`
    })
    
    export class DuplicateComponent {
        clickMessage = '';
        onKey(value: string) { }
    
        onClickMe() {
            this.clickMessage = 'You are my hero!';
        }
    }
    

    您的逻辑似乎仍然有点不对劲,但我认为您正在寻找以下方面的东西:

    http://plnkr.co/edit/jcl7kZ4MzRBtL5WykoJj?p=preview

    【讨论】:

      【解决方案2】:

      较旧的测试版存在错误。尝试更新到最新的 angular2 版本。

      【讨论】:

      • 如何更新到最新版本。现在是测试版吗?
      猜你喜欢
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多