kdocs
GitHub
Lang - Web
Lang - Web
  • Base
    • Css
    • Javascript
    • Typescript
      • New Project
  • Frameworks
    • Angular
      • Directives
      • Components
      • Templates
        • Bindings
        • Control Flow
        • Variables
      • Signals
      • Pipes
      • Services
        • Dependency Injection
      • Forms
        • Reactive Form
        • Template-Driven Form
      • Router
      • HTTP Client
      • Observables RxJS
      • Testing
        • Components
        • Directives
        • Pipes
        • Services
      • Optimization & Performance
      • Security
Powered by GitBook
On this page
  • Text Interpolation {{ }}
  • Property Binding []
  • Attribute Binding [attr.]
  • Class Binding [class.]
  • Style Binding [style.]
  • Event Binding ()
  • $event Argument
  • Binding to Keyboard Events
  • Two-way Binding [()]
  • Usage in Form Controls
  • Usage between Components (Signals)
  • Usage between Components (Old way)
  1. Frameworks
  2. Angular
  3. Templates

Bindings

PreviousTemplatesNextControl Flow

Last updated 5 months ago

Bindings creates a live connection between Template (UI, DOM element) elements and the Model (the component instance to which the template belongs).

The Change Detection algorithm is responsible for keeping the View and Model in sync.

Text Interpolation {{ }}

Refers to embedding expressions into marked up text.

You can type any expressions that can be resolved or converted to a string, not only variable names.

Objects and Arrays passed are converted using the valu's toString method.

<p>{{ id }}</p>
<p>{{ 'hW71245fa' }}</p>
<p>{{ id === '' ? 'as98f6a98' : id }}</p>
<p>{{ returnID() }}</p>

Helps you set values for properties of native HTML elements or Angular's Directives.

It moves a value in one direction.

The brackets [], cause Angular to evaluate the right-ahdn side of the assignment as a dynamic expression. (Without it, Angular treats it as a string literal)

<button [name]="name" [disabled]="!allowClick">Click</button>

Attribute Binding [attr.]

Helps you set values for attrubutes directly.

Resembles property binding, but instead of an element property between brackets, you precede the name of the attribute with the prefix attr.

When the expression resolves to null or undefined, Angular removes the attribute.

<tr>
    <td [attr.colspan]="expression"></td>
</tr>

Class Binding [class.]

Use class bindings to conditionally add and remove CSS class on elements based on whether the bound value is true or false.

Angular does not guarantee any specific order of CSS classes on rendered elements.

Remember that when working with Objects, Arrays, Map or Set, the identity of the object must change for Angular to recognize the update.

Mutation of these objects will not trigger Change Detection.

If an element has multiple bindings for the same CSS class, Angular resolves collisions by following its style precedence order.

Binding to a single Class

<p [class.sale]="addClass"></p>

Binding to multiple Classes

<!-- Only write `class` -->
<p [class]="classExpression"></p>

classExpression can be:

  • string: With one or more space-delimited class names.

  • {}: An object with class names as keys and truthy or falsy expressions as values determining if the given class should be applied or not.

  • []: An array of class names as strings.

Style Binding [style.]

Remember that when working with Objects, Arrays, Map or Set, the identity of the object must change for Angular to recognize the update.

Mutation of these objects will not trigger Change Detection.

If an element has multiple bindings for the same CSS class, Angular resolves collisions by following its style precedence order.

Binding to a single Style

You may add a unit extension like em or %.

<p [style.background-color]="expression"></p>
<p [style.backgroundColor]="expression"></p>

Binding to multiple Styles

<!-- Only write `style` -->
<p [style]="styleExpression"></p>

styleExpression can be:

  • string: A string list of styles like:

    • width: 100px; height: 100px; background-color: cornflowerblue;

  • {}: An object with style names as the keys an styles values as the values:

    • {width: '100px', height: '100px', backgroundColor: 'cornflowerblue'}

  • Binding arrays is not supported.

Lets you listen for and respond to user actions such as keystrokes, mouse movements, clicks and touches.

The syntax consists of a target event name within () to the left of an equal sign, and a quoted template statement to the right.

<button (click)="handleClick()"></button>

To determine an event target, Angular checks if the name of the target event matches an event property of a known directive.

If myClick fails to match an output property of a Custom Directive, Angular will instead bind to the myClick event on the underlying DOM element.

<button (myClick)="handleClick()"></button>

$event Argument

In every template event listener, Angular provides a variable named $event that contains a reference to the event object.

@Component({
    template: `
        <input type="text" (keyup)="updateField($event)" />
    `,
})
export class AppComponent {
    updateField(event: KeyboardEvent): void {
        console.log(`The user pressed: ${event.key}`);
    }
}

Binding to Keyboard Events

You may specify the key or code that you would like to bind to.

By default event bindings will assume you will use the key field of the keyboard event. You can also use the code field.

The code is more specific than the key.

Combinations of keys can be separated by a ..

Depending on the OS, some key combinations might create special characters instead of the key combination you would expect.

Use code keyboard event field to get the correct behavior.

<input (keydown.enter)="handleKeyDown()" />
<input (keydown.shift.enter)="handleKeyDown()" />
<input (keydown.alt.a)="handleKeyDown()" />
<input (keydown.ctrl.h)="handleKeyDown()" />
<input (keydown.ctrl.alt.h)="handleKeyDown()" />
<input (keydown.shift.ctrl.k)="handleKeyDown()" />
<!-- For MAC -->
<input (keydown.command.enter)="handleKeyDown()" />

<!-- With Codes -->
<input (keydown.code.shiftleft.ctrlleft.keyk)="handleKeyDown()" />

It is a shorthand to simultaneously bind a value into an element, while also giving that element the ability to propagate changes back through this binding.

Use it to listen for events and update values simultaneously between parent and child components.

<app-sizer [(size)]="fontSizePx"></app-sizer>

Usage in Form Controls

#Broken link in forms

Usage between Components (Signals)

Usage between Components (Old way)

Use model() signal function instead.

For it to work, the @Output property must use the pattern, inputChange, where input is the name of the @Input property.

  • For example:

    • If @Input size!: number | string, so data can flow into the Component.

    • Then @Output sizeChange = new EventEmiter<number>(), which lets data flow out of the Component, to it's parent.

@Component({ ... })
export class Component {
    @Input() size!: number | string;
    @Output() sizeChange = new EventEmitter<number>();

    resize() {
        this.size = ...;
        this.sizeChange.emit(this.size);
    }
}

Property Binding []
Event Binding ()
List of codes.
List of keys.
Two-way Binding [()]
More info here.