我是Angular 2的新手。我刚刚创建了一个角度为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中多次使用'<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>
答案 0 :(得分:4)
发生这种情况的原因是因为您正在尝试引导具有多个实例的根元素。来自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!';
}
}
看起来你的逻辑仍然有点偏离,但我认为你正在寻找这些方面的东西:
答案 1 :(得分:0)
旧版测试版中存在错误。尝试更新到最新的angular2版本。