Deadpool
Deadpool

Reputation: 8240

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:

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)]?

Upvotes: 3

Views: 285

Answers (3)

Zircon
Zircon

Reputation: 4707

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.

Upvotes: 2

Jens Habegger
Jens Habegger

Reputation: 5446

[(ngModel)] is a 'convenience' directive used by Angular to simplify two-way binding by combining a attribute directive and an event-listener. It doesn't really belong into any of the directive groups you mentioned, but it's also not a group of its own.

Using the @Directive Decorator, you could also create your own directives, the types offered by the Angular Documentation are probably meant to ease the entry into Angular (.. or in your case, offer potential for confusion ;-) )

Upvotes: 2

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

[(NgModel)] is a attribute directive combined with the event listener. This [(NgModel)] is a shorthand of:

[ngModel]="variable" (ngModelChange)="variable = $event". As you see, behind the scenes it hides something similar to the EventEmitter. So it binds variable to the template and also listens for a change event in both - template and model.

Upvotes: 2

Related Questions