Data Binding

Interpolation

  • Use double braces

  • Weaves calculated strings into the text between HTML elements

  • Attributes can be assigned - <img src="{{heroImageUrl}}" style="height:30px">

  • One way data binding

  • Can be expressions like {{price * units }}

  • Can call a function {{ calculateTotal() }}

  • Can use component or template variables

Setting Component Properties

Passing values to a component can be handled using @Input() decorator on the child component. Parent components can pass data to their child components using attributes.

child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() people: string[];
@Input() total: number;
}
parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `<app-child [people]="people" total="123"></app-child>`,
styles: []
})
export class ParentComponent {
people: string[] = ['Bob', 'Mike', 'Jim'];
}

The attribute name can be different than the variable name by passing a string name to the Input decorator: Input("employees") people: string[];

Property bindings

Values are bound to a component with and without square brackets around the Input name in the template.

When passing data to an Input property that is declared in the template no square brackets are required.

<component name="angular"></component>

When passing data that's a property on the component or declared from the structural directive, it must be wrapped with square brackets.

<component [name]="names.angular"></component>

DOM Element Properties

DOM Element properties can be set to variables using bracket notation.

Summary

  • Interpolation

  • Passing values to a component

  • Setting DOM Element properties