Search code examples
javascriptangularngmodel

Confused as [(ngModel)] doesn't fall in any of the Directive Categories in Angular4


As per Angular Docs the Directives of Angular are of 3 types:

  • Components
  • Structural
  • Attribute

As per the following official link: https://angular.io/guide/attribute-directives#directives-overview

1. Components

<home></home>
<about-us></about-us>
<support></support>

2. Structural Directives

<div *ngIf="age < 18"> ... </div>
<div *ngFor="let x of students"> ... </div>

3. Attribute Directives

<div [ngClass]="red"> ... </div>
<div [ngStyle]="{'background':colorValue}> ... </div> 

Now, my problem is that [(ngModel)] is a directive, but I am confused as it doesn't seem to fall in any of the above 3 categories (as per official documentation), and there is no 4th category! So, can someone point out what kind of directive is [(ngModel)]?


Solution

  • NgModel is an Attribute Directive. It is applied as an attribute to (almost) any element in your DOM.

    The doc for NgModel shows that its selector is [ngModel]..., which means it is applied as an attribute to (almost) any element in your DOM.

    The official article that you linked summarizes the three categories:

    Components — directives with a template.

    Structural directives — change the DOM layout by adding and removing DOM elements.

    Attribute directives — change the appearance or behavior of an element, component, or another directive.

    When you put [(ngModel)] on an element, you are modifying its behavior by associating inputs and outputs with it (see @JensHabegger 's answer). The "banana in a box" is syntactic sugar for two-way binding which is detailed here. Essentially, you are applying [ngModel] with an input, then automatically modifying a value based on its output.

    As such, NgModel is definitely an attribute directive.