Christian De Lorence
Christian De Lorence

Reputation: 69

Ambiguity about Angular component decorator behavior describes as in Angular documentation

I am new to angular and currently i have gone through some examples which is given by angular.io site. But in the component decorator explaination with in the documentation, it states that

Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated per an element in a template.

What they actually mean by only one component can be instantiated per an element in a template.

Can any one explain me this please.

Upvotes: 2

Views: 253

Answers (2)

Aravinda Meewalaarachchi
Aravinda Meewalaarachchi

Reputation: 2629

This actually it means that within the angular ecosystem, Only one component will instantiated per an element (selector) within a template. Check following example.

//app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div style="text-align:center">
          Welcome to {{ title }}!
    </div> `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Test App';
}

try to use two selector tags within the index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular App</title>
  <base href="/">    
</head>
<body>
  <app-root></app-root>
  <app-root></app-root>
</body>
</html>

As a result, You will be see only one Welcome to the Test App rendered in browser. There can only ever be one component per html element

Upvotes: 1

Chunbin Li
Chunbin Li

Reputation: 2244

only one component can be instantiated per an element in a template.

AppComponent can be instantiated to the element(<my-app>) in the DOM

online example

enter image description here

Upvotes: 1

Related Questions