left-icon

Angular Succinctly®
by Joseph D. Booth

Previous
Chapter

of
A
A
A

CHAPTER 16

Editing Data

Editing Data


In the soccer example from the last chapter, the Standings component only displayed the data; it did not allow you to edit or update the data at all. For scoring, we need to look up data from a drop-down list, and then allow a user to edit the scores. Finally, the new scores need to be written back to the component. For this, we need to dig deeper into data binding.

Data binding

Data binding is the linking of properties from your component to your generated template HTML. You’ve seen one example with interpolation, where the property values between the braces {{ }} are bound to display elements within the HTML.

Property binding

Another method of binding is to assign a component property to an HTML property. For example, if you wanted to bind the name of the club into an input text, you could use the following syntax.

Code Listing 130

[HTML property]="Component property"

Code Listing 131

<input type="text" [value]="ClubOwner" >

You are not limited to text boxes; you can bind to styles, properties, classes, and more. For example, you might have an <img> tag that represents an avatar or photo for a person. The [src]="personAvatar" could be used to display the person’s avatar or photo in an HR system.

Attribute binding

Attributes in HTML are used to initialize various elements’ properties. They are assigned when the HTML is written. When the DOM is built, it converts many of the attributes to properties for manipulation in your client-side code. However, attributes set in HTML are always strings, while the DOM property that corresponds to the attribute can be any data type.

You can use the attr.name syntax to update the string value of the attribute, although sometimes that might not give you the intended effect. For example, the disabled attribute must be removed, not simply set to an empty string. In general, the property binding should be used to manipulate the DOM behavior.

Code Listing 132

<button [attr.disabled]="true"> Discard changes </button>

If you want to enable the button, you would have to remove the disabled attribute, not simply set the attr.disabled to false (which will have no effect). Fortunately, there is also a property called disabled, which can be manipulated using the property binding.

Code Listing 133

<button [disabled]="FoundChanges"> Discard changes </button>

Event binding

If you want to bind a statement to an event of an element, you enclose the event name in parentheses. This is how you would create an association between any event and your component code. For example, if you have a Save button, you could use the following syntax to call your component’s save method when the button is clicked.

Code Listing 134

<button (click) = "SaveData()" > Save changes </button>

Common events you might want to bind include:

  • blur: User leaves an input field.
  • focus: User enters an input field.
  • submit: User clicks a button that submits the form.
  • change: User changes value of an input element.

There are other events, such as key up, key down, and window resize.

When the event method is called, a parameter called $event is available to the method. The contents of the $event object will vary based on the DOM element and the event called. For example, the input event has a property called target.value, which contains the content of the input field.

Class binding

Class binding allows your component to specify a class name. For example, imagine we have two classes: one for current accounts, and one for past-due accounts. Inside your component, you have a method called InvoiceClass() that returns a string, either Current or PastDue.

The following syntax would let the component set the color for each invoice in the template code.

Code Listing 135

<span [class]="InvoiceClass" > {{ InvoiceNumber }} </span>

You can also bind a class name to a Boolean component property or function. For example, we might show the top three scorers with a class name called Top3. Once the fourth-highest scorer is found, we want to remove the class.

Code Listing 136

<span class="Top3" [class.Top3]="InTopThree"> {{ PlayerName }} </span>

Once the InTopThree method returns false, the Top3 class will no longer be applied to the player name span.

Style binding

The style binding allows you to use a function or expression to apply a style to an element. For example, imagine we had a list of find results, but any results more than 30 days old should appear a bit faded.

Code Listing 137

<span [style.background-color]="isOver30 ? 'antiquewhite','white'> {{article}} </span>

In this example, the Boolean component public property, isOver30, is evaluated. If true, then the style for the background color is set to antiquewhite; otherwise, it is set to white. The general syntax is:

Code Listing 138

[style.style property name] = "expression" | function | style value

One-way binding summary

Here are some examples of one-way binding, all following the same general syntax:

  • [target] (Can be a property, class, style, etc.)
  • (target) (Event name)
  • = "expression or statement"

The one-way binding specifies the target and the expression, function, or inline statement that should be tied to the target object. The key takeaway is that the component provides the target value, which is either a function or a property value. However, the target value is not explicitly returned or updated in the component.

Our next section discusses two-way binding techniques, which get data back AND forth from the template page to the component.

Note: When writing component functions that return values for the target, be sure that the data type matches the expected value. In addition, the function should be simple and not impact other component variables that might be referenced in other bindings.

Interpolation and property binding can perform the exact same functionality; behind the scenes, Angular converts interpolations to property bindings. There is no reason to choose one method or the other; however, I would suggest that you lean toward readability and be consistent with your usage.

Two-way binding

Two-way binding is used to both display a component property and update the property when the user makes changes while in the template. Two-way binding is a combination of a property binding and an event binding. For example, the following syntax would display the value of FirstName in the input element’s value field, and would also respond to the input event by updating the property with the value the user entered.

Code Listing 139

<input id="FirstName"  [value]="FirstName"

           (input)="FirstName = $event.target.value" />

While this will work properly, it requires a lot of extra work, and you duplicate the property name. Fortunately, Angular provides a syntax that makes the binding a bit easier.

ngModel

The ngModel directive provides a simpler syntax for two-way data binding. It is found in the Angular/forms library, so you will need to add the import to your app module file, and the import metadata in the @ngModule declaration.

Code Listing 140

 import { FormsModule } from '@angular/forms';

Code Listing 141

imports:      [ BrowserModule,routing,FormsModule ],

These two changes will allow components to use the ngModel directive to create data binding. The basic syntax is:

Code Listing 142

[(ngModel)] = "component property"

This shorthand directive performs the property and event binding (note the brackets and parentheses) for your template. You will also need to make sure that the input element has a name property as well, so Angular can properly map the component to the HTML element.

Code Listing 143

        <input type="number" 

  [(ngModel)]="AwayScore" name="AwayScoreVal" />

The HTML name element does not have to match the component name; Angular just needs the name element to perform the binding.

Summary

The binding techniques let you enhance your basic HTML in your template code to produce displays and input of your component data. In the next chapter, we will combine these techniques to create a component to record scores for our soccer club application.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.