How to reuse angular component multiple times

I'm learning the basics of angular, but I still can't figure out how to reuse the same component over and over in the same document.

This is the relevant code:

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>

      

and this is the main 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>

      

The problem is that I wanted angular to add a component to each "example" tag in index.html. But I see that it only works for the first tag and the rest are ignored. Can you help me understand this behavior?

early

+3


source to share


1 answer


The problem is that in your application example

is the root component. Angular only handles one DOM element for the root component at the top level. This is how you can modify your template example

to view it multiple times:

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

<!-- rendered multiple times -->
<b-comp></b-comp>
<b-comp></b-comp>

      

And add BComponent

to your application:



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

export class BComponent {
}

      

And add it to declarations

in AppModule

:

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

      

+4


source







All Articles