Setting up custom values declaratively

You will probably agree on the fact that having the functionality of setting up custom countdown timers would be nice, right? Input properties turn out to be an excellent way to achieve this. In order to leverage this functionality, we will have to tweak the import statement at the top of the file:

import { Component, Input } from '@angular/core';

@Component({
selector: 'countdown-timer',
template: '<h1>Time left: {{ seconds }}</h1>'
})
export class CountdownTimerComponent {
@Input() seconds : number;
intervalId;
// rest of the implementation remains the same
}

You might have already noticed that we are no longer initializing the seconds field, and it is now decorated with a property decorator (as we saw in Chapter 3, Introducing TypeScript). We have just started to define the API of our component.

Property naming is case sensitive. The convention enforced by Angular is to apply camel case to component input and, as we will see shortly, output properties alike.

Next, we just need to add the desired property in our container component's template:

@Component({
selector: 'timer',
template: `
<div class="container text-center">
<countdown-timer [seconds]="25"></countdown-timer>
</div>`
})

Please note that we have not updated the TimerComponent at all. We only updated its CountdownComponent child component. However, its brand new API becomes available to any component that eventually includes it in its own template as a child component, so we can set up its properties declaratively right from the template, or even bind a value imperatively from a property located in the TimerComponent controller class if we wish.

When flagging a class property with @Input(), we can configure the name we want this property to have upon instantiating the component in the HTML. To do so, we just need to introduce our name of choice in the decorator signature, like this: @Input('name_of_the_property'). In any event, this practice is discouraged since exposing property names in the component API distinct from the ones defined in its controller class can only lead to confusion.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset