【问题标题】:How to reuse an angular component multiple times如何多次重用一个角度组件
【发布时间】: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


【解决方案1】:

问题在于,在您的应用程序中,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>

并将BComponent 添加到应用程序中:

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

export class BComponent {
}

并将其添加到AppModule 中的declarations

@NgModule({
   imports:      [ BrowserModule ],
   declarations: [ AppComponentl, BComponent ],
   bootstrap:    [ AppComponent ]
})

【讨论】:

  • 嗯,我想我明白了,但我不能把一个工作的例子放在一起
  • 你得到什么错误?您还需要在AppModule 中引用BComponent,我将此信息添加到答案中
  • 没有显示错误,但该示例根本不起作用。我对角度的经验很少,我按照指示添加了一个新的 b.component.ts 和 b.module.ts 。我已经按照您的建议修改了 test.component.html。我必须更改 index.html 中的任何内容吗?感谢您的耐心等待。
  • 也许我没有正确解释自己,我需要将“

    +

  • @rekotc,好吧,在我的示例中,&lt;span&gt;b-comp&lt;/span&gt; 将重复 2 次,因为它是 BComponent 的模板。只需将您需要的任何 html 放入 BComponent
猜你喜欢
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
相关资源
最近更新 更多