webworm
webworm

Reputation: 11019

Angular component HTML template contains reference to itself

I am looking over the Angular code of a co-worker, who is much more knowledgeable than myself when it comes to Angular, in an effort learn more.

One of the things that is really confusing me is the use of the component's selector in the HTML template of the component itself.

widgetA.component.ts

import {
    Component,
    OnInit,
    Input,
    HostListener
} from '@angular/core';

// other imports here

@Component({
    selector: 'widgetA',
    templateUrl: './widgetA.component.html',
    styleUrls: ['./widgetA.component.scss']
})
export class WidgetAComponent implements OnInit {
    @Input() property1!: string;
    @Input() property2: string;

    // remainder of class here
}

widgetA.component.html

<div>
<!-- other HTML here -->
  <widgetA
    [property1]="value1" 
    [property2]="value2"
  ></widgetA>
  <widgetB
    [property3]="value3" 
    [property4]="value4"
  ></widgetB>
<!-- other HTML here -->
</div>

I have to assume this is allowable because webpack successfully compiles the code. I guess I am wondering if this is typical in angular? Is it a design pattern? It seems confusing to me to include a reference to a component in the HTML template of the component itself.

Upvotes: 2

Views: 1486

Answers (2)

Keenan Diggs
Keenan Diggs

Reputation: 2342

This confused me when reading it also, but check out this response: In which way does Angular resolve duplicate directive/component selectors?

Basically, 'widgetA' in the template is a reference to a component imported from another module. If you tried to have the same component reference itself, the application would be stuck in a recursive loop and never resolve. This was the case in a single-component stackblitz I tried to create, and it became unresponsive.

Edit:

Stackblitz demo of the failure: https://stackblitz.com/edit/angular-2zcgz8

This is the console error when recursively calling a component in the manner you've described: enter image description here

Basically, in my example I have a SomeComponent class with @Component decorator and the selector 'some' like so:

@Component({
  selector: 'some',
  templateUrl: './some.component.html'
})
export class SomeComponent {
  @Input() input1: string;
  @Input() input2: string;
}

And my some.component.html contains:

<p>{{input1}}<p>
<p>{{input2}}</p>

<some [input1]='hi'></some>

Upvotes: 2

Samer Ayoub
Samer Ayoub

Reputation: 1001

The selector is not a reference to the component, it is just a tag name specified in the component class to be able to use this component in our markup by using a like HTML tags. The confusion comes from using the same name "widgetA" for the component class name and the selector name So If you change selector to another name say "widA" in both .ts and .html files it still works !!

Upvotes: -1

Related Questions