如何多次重用角度组件

rek*_*otc 4 javascript components angular

我正在学习 angular 的基础知识,但我仍然无法弄清楚如何在同一个文档中多次重用同一个组件。

这是相关代码:

测试模块.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 { }
Run Code Online (Sandbox Code Playgroud)

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";
  }
}
Run Code Online (Sandbox Code Playgroud)

测试组件.html

<h1>Hello {{name}}</h1>
<button (click)="changeName()">Click me!</button>
Run Code Online (Sandbox Code Playgroud)

这是主要的 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>
Run Code Online (Sandbox Code Playgroud)

问题是:我希望 angular 将组件添加到 index.html 中的每个“示例”标签。但我看到它仅适用于第一个标签,而其他标签则被忽略。你能帮我理解这种行为吗?

提前致谢

Max*_*kyi 6

问题是在您的应用程序中example是根组件。Angular 只为顶层的根组件处理一个 DOM 元素。以下是如何修改example模板以查看它多次呈现的方法:

<h1>Hello {{name}}</h1>
<button (click)="changeName()">Click me!</button>

<!-- rendered multiple times -->
<b-comp></b-comp>
<b-comp></b-comp>
Run Code Online (Sandbox Code Playgroud)

并添加BComponent到应用程序中:

@Component({
  selector: 'b-comp',
  template: `<span>b-comp</span>`
})

export class BComponent {
}
Run Code Online (Sandbox Code Playgroud)

并将其添加到declarationsin AppModule

@NgModule({
   imports:      [ BrowserModule ],
   declarations: [ AppComponentl, BComponent ],
   bootstrap:    [ AppComponent ]
})
Run Code Online (Sandbox Code Playgroud)