簡體   English   中英

如何多次重用角度分量

[英]How to reuse an angular component multiple times

我正在學習角度的基礎知識,但我仍然無法弄清楚如何在同一文檔中多次重復使用相同的組件。

這是相關代碼:

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中的每個“example”標記。 但我發現它僅適用於第一個標簽,而其他標簽則被忽略。 你能幫助我理解這種行為嗎?

提前致謝

問題是在您的應用程序中,該example是根組件。 Angular在頂層只處理根組件的一個DOM元素。 以下是如何修改example模板以查看多次呈現的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 {
}

並將其添加到AppModuledeclarations

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM