Angular 10 Tutorial - Property Binding

In this tutorial, we will learn about property binding in Angular 10. Property binding is used to pass data from the component class (component.ts) and set the value of a given element in the user-end (component.html). Property binding is an example of one-way data binding, where the data is transferred from the component to the class.

Implementing Property Binding in Angular 10

Let's see how we can do property binding in Angular 10. Switch to the project and open the app.component.html file. Now, let's create some input text fields:


<input type="text" name="firsnum" />
<input type="text" name="secondNum" />

Now, let's create the properties. Open the app.component.ts file and create the properties:


firstNum=0;
secondNum=0;
Sum = 0;

Now, let's bind these properties with the input text fields and also create a button:


<input type="text" name="firsNum" #firstNum [value]="firstNum" />
<input type="text" name="secondNum" #secondNum [value]="secondNum" />
<button >Sum</button>

Creating a Function to Perform an Action

Let's create a function inside the app.component.ts file:


getSum(num1,num2){
this.sum = parseFloat(num1) + parseFloat(num2);
}

Now, call this function on the button. Go to the app.component.html file and call the function from the button:


<button (click) = "getSum(firstNum.value,secondNum.value)">Sum</button>

Now, let's display the result. Write:


<h1>Sum of Two Number {{sum}}</h1>

Now, let's check. Switch to the browser. Enter the first number, let's say 18, and the second number is 20. Now, click on the button, and you can see the addition of the two numbers is 38. Just try another number, so enter a new number, let's say 26 and 45, and click on the sum button, and you can see the result 71.

So, in this way, you can bind properties in Angular 10.