Two-way data binding in Angular

In Angular, you can make it so that as you type text into an input, that text automatically gets put into a class property. This is called two-way data binding.

For this binding to work, you first need to enable it. To do this, import FormsModule in the component file:

app/app.component.tsimport { FormsModule } from '@angular/forms';

And then we add to the imports property of the @Component decorator:

app/app.component.ts@Component({
  selector: 'app-root',
  standalone: true,
  imports: [FormsModule, UserComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})

After this, two-way data binding will be enabled and we can use it. Let's do it.

First, we declare a class property that we will then two-way bind:

app/app.component.tsexport class AppComponent {
  public text: string = '';
}

Let's say we have a div and an input. Let's say some class property is output in the div:

html<div>
  {{ text }}
</div>
<input>

Let's bind our text property to the input change. To do this, you need to write a special [(ngModel)] directive in the input, the value of which should indicate the property of our class:

html<div>
  {{ text }}
</div>
<input [(ngModel)]="text">

Now if you run the code and start typing text into the input, that text will immediately start displaying in the div.

Задание 1

Given an input and a paragraph. A number is output to the input. Make it so that as you type a number into the input, the square of that number is displayed in the paragraph.

Задание 2

You are given two inputs and a paragraph. Numbers are entered into the inputs. Make the paragraph display the sum of the numbers entered.