Angular Components

Components play a central role in Angular, with the Angular application consisting of a tree of components.

Selector

The selector is placed in a HTML block to specify where the Angular Component should be displayed. Assuming we have an Angular Component named app-stock-item, here is how the component is declared in the HTML:

  • app-stock-item: the component would be used as <app-stock-item></app-stock-item> in HTML.

  • .app-stock-item: this component would be used as a CSS class like <div class=”app-stock-item”></div> in HTML.

  • [app-stock-item]: this component would be used as an attribute in HTML.

Change Detection Strategy

Default

  • The default strategy is that Angular will check all components for data binding changes and update components accordingly.

  • This can be a performance hit for large components.

OnPush

  • If the current component does not depend on any external data changes, it can set ChangeDetectionStrategy to OnPush.

  • Angular does not worry about changes from external components affecting the current component.

  • This provides a performance boost for applications if this is the case.

View Projections

@Input allows for variable values to be passed down from the parent component to the child component. But what happens if the parent component wants to pass down something more complex than that?

That’s where View Projections can help. The way it works is as follows.

Parent Component

<!-- Other HTML tags can go here -->
<child-component-selector>
  <!-- The view projection UI components that
  the parent wants the child to display -->
</child-component-selector>

Child Component

<div>
  <!-- This is where the projection goes -->
  <ng-content></ng-content>
</div>
  • The two code blocks provided above show how the parent template can dictate what can be projected in the child component.

  • The stuff to be project is defined in the parent template between the child component’s selector tags.

  • The child template uses the <ng-content> tags to specify where the view projection would be shown.