问题
I'm learning the basics of angular, but i still can't figure out how to reuse the same component multiple times 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: i wanted angular to add the component to every "example" tag in index.html. But i see it works only for the first tag while the others are ignored. Can you help me to understand this behaviour?
thanks in advance
回答1:
The problem is that in your application the example
is the root component. Angular process only one DOM element for the root component at the top level. Here is how you can modify your example
template to see it rendered 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
into the application:
@Component({
selector: 'b-comp',
template: `<span>b-comp</span>`
})
export class BComponent {
}
And add it to the declarations
in AppModule
:
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponentl, BComponent ],
bootstrap: [ AppComponent ]
})
来源:https://stackoverflow.com/questions/44071244/how-to-reuse-an-angular-component-multiple-times