Angular
Fundamentals of Angular Directives - Component Directives
  •  

Component Templates

PRO
Outline

Angular Templates

Component templates are HTML + Angular = Awesomesauce. We'll leverage our existing skill of writing HTML for templates on the web plus add the power of Angular using built-in directives plus our own attribute, structural and component directives to compose applications using a modular approach.

Property Binding

We can set the value of a property of an HTMLElement via property binding using square-bracket ( [] ) syntax in a template.

For example, we can set the innerHTML property of an HTMLParagraphElement in a template:

@Component({
  template: `
      <p [innerHTML]="html"></p>
    `
})
export class AppComponent {
  html = 'Hello, World!';
}

In the code above we are setting the innerHTML to the value of the html property in the component, which is "Hello, World!".

Event Binding

We can add event listeners in our template using event binding in Angular. We'll accomplish this using parenthesis syntax with the event name in our templates. When the event occurs, we will invoke the expression that is specified.

For example, let's add an event binding for the click event to a <button> in a template:

@Component({
  template: `
      <button (click)="selected = !selected"></button>
        <p>Selected: {{ selected }}</p>
    `
})
export AppComponent {
  selected = true;
}

In this example, we toggled the value of the selected property in our component when the click event occurs on the <button> in the template.

 

I finished! On to the next chapter