【发布时间】:2017-10-19 15:42:32
【问题描述】:
我正在学习 Angular 的基础知识,但我仍然不知道如何在同一个文档中多次重用同一个组件。
这是相关代码:
test.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './test.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
test.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'example',
templateUrl: "./test.component.html",
styleUrls: ["./test-common.css"],
})
export class AppComponent {
name = 'Angular';
changeName() {
this.name = "duck";
}
}
test.component.html
<h1>Hello {{name}}</h1>
<button (click)="changeName()">Click me!</button>
这是主要的 index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<example>Loading ...</example>
<example>Loading ...</example>
<example>Loading ...</example>
<example>Loading ...</example>
</body>
</html>
问题是:我希望 Angular 将组件添加到 index.html 中的每个“示例”标签。但我看到它只适用于第一个标签,而其他标签则被忽略。你能帮我理解这种行为吗?
提前致谢
【问题讨论】:
-
只要关注“英雄之旅”angular.io/docs/ts/latest/tutorial
-
我已经按照该教程进行操作,它使用 ngFor 加载同一组件的多个副本。但我想看一个例子,每次有一个“例子”标签时,角度加载组件
-
你可以在你的 app.component 中完成
标签: javascript angular components