We will learn about using Angular 2's new Property Binding syntax with TypeScript. Learn to bind to DOM properties with your Angular 2 application.
Today we're going to go over property binding in Angular 2. Before we get started, if you want to have the same environment and code that I have, you can do so by going to angular.io and clicking the "Learn in Five Minutes" button. This code is the result of the walkthrough found on that site. Also important to know is that all code today we're writing is in typescript. When we bind the properties in Angular 2 we're actually binding to properties of DOM elements.
This is the same type of property manipulation that happens when you write CSS for your websites or Web apps. In this example we're going to bind to the hidden property of the H1 element. In order to do this we're going to use the special Angular 2 syntax of brackets. We surround the property we're binding to with brackets, and then set the value of it. We're going to go and set hidden = true. If we go over to our browser and refresh the page, we'll see that "Hello, Alice," has now disappeared.
To verify this has happened because we've set the hidden property to true, let's go ahead and create a duplicate and we'll set it to false. We'll change this one to "Goodbye, Alice," so we can see which version is working. Let's refresh the page again and we'll see that "Goodbye, Alice," now shows because we've set hidden to false. Again, let's just quickly set "Hello, Allice," to false so that we can see now that both are showing. We don't actually have to write true or false as the value for these properties.
We can reference expressions within our component. Let's go ahead and create a new variable which will be a Boolean, and we'll call it hidden. In our constructor we'll say this.hidden = true. Now we can reference hidden instead of writing true or false. Let's go ahead and set "Hello, Alice" to hidden, we'll refresh the page and see that it has disappeared. We'll go down, change that to false, refresh the page again and we'll see that it has reappeared. We are not limited to the bracket notation of Angular 2.
They also make available to us the directive notation that you're used to from Angular 1.x. We can do bind-hidden, it will have same results as brackets around the property. Let's go ahead change the value again, just to make sure that it's working, refresh the page, and we'll see that Hello, Alice has disappeared. So this is a working example of using both property binding syntaxes provided by angular 2, both bind- or the bracket notation.
One example of this is the ngShow that we're used to from Angular 1.x. By binding to the hidden property, we now have the same capabilities as we did with ngShow and ngHide. There are many DOM properties that are available to use besides hidden. A few examples of those are id, innerHTML, class name and so forth. It's important to become familiar with these properties so you can Angular 2 to the fullest.