如何在Angular 2中多次调用组件
问题描述:
我是Angular 2中的新成员。我只是在角2中创建了一个基本组件。组件正在工作,但是当我在HTML中多次调用该组件时,它仅适用于第一次调用。如何在Angular 2中多次调用组件
下面是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多次使用'<click-me></click-me>'
,它适用于第一个。
下面是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>
答
发生这种情况的原因是因为您试图引导具有多个实例的根元素。在角2角,从1的到来,认为bootstrap
方法作为ng-app
相当于角1
为了解决这个问题,只需创建一个新的组件,并将其导入到你的根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!';
}
}
它仍然出现在您的逻辑是有点过,但我认为你正在寻找沿着这些方向的东西:
答
有老年beta版本的bug。尝试更新到最新的angular2版本。
我如何更新到lattest版本。它现在在测试版吗? – sarath
更新了npm更新 – muetzerich
。但仍然有问题。 :-( – sarath