¿Qué es el enlace de datos bidireccional en Angular
El enlace de datos bidireccional en Angular permite que los datos fluyan desde el componente a la vista y viceversa. Se utiliza para mostrar información al usuario final y le permite realizar cambios en los datos subyacentes mediante la interfaz de usuario. Esto crea una conexión bidireccional entre la vista (la plantilla) y la clase de componente que ya mencionamos. El proceso es similar al enlace bidireccional de WPF.
How does data binding work in Angular?
Angular enlace de datos funciona sincronizando los datos de los componentes angulares con la interfaz de usuario. De esta manera, siempre puede mostrar el valor actual de los datos. En cuanto al enlace bidireccional, la sincronización automática de datos se produce entre el modelo y la vista, manteniendo ambos sincronizados todo el tiempo. Debido a esto, cualquier cambio realizado en el modelo también se refleja inmediatamente en la vista. Y viceversa: los cambios realizados en la vista también se actualizan en el modelo. El enlace de datos bidireccional en Angular se usa para mostrar información al usuario final y permite al usuario final realizar cambios en los datos subyacentes mediante la interfaz de usuario. Esto crea una conexión bidireccional entre la vista (la plantilla) y la clase de componente. Esto es similar al enlace bidireccional en WPF.
Un enlace unidireccional toma el estado de nuestra clase de componente y lo muestra en nuestra vista. Veamos este código:
<input #myTitle (keyup)="keyup(myTitle.value)">
<h2>{{ text }}</h2>
export class SampleComponent implements OnInit {
text = 'default value';
keyup(value) {
this.text = value;
}
...
Here we are simply using interpolation to bind the text property to the HTML. This will display the value of the text property in the UI. The input element handles the user interaction and updates the underlying text property through the UI by using the event binding. Essentially, the input does the opposite of the one-way binding, it takes the information from the UI and updates the property in the component class. The method which is hooked up to the input's keyup event updates the text property each time the event occurs. Once the text property value is changed by the event method, that change is reflected in the UI by the one-way binding using interpolation of the h2 element. So if the user types something into the input element, that will immediately update the h2 text - this behavior is basically a simulation of a two-way binding. The same can also be achieved in WPF by using a one-way binding and a keyup event handler, but the two-way binding is way more convenient to use.
How to implement two-way data binding in Angular
Afortunadamente, podemos implementar la lógica del ejemplo anterior de una manera mucho más sencilla y aquí es donde interviene el enlace bidireccional.
The direction of a two-way binding is not just component class to UI, but UI to component class as well. To achieve this, we are going to use a directive called ngModel. Let's update the sample from above with the ngModel directive. The syntax for that is - an open bracket followed by an open parenthesis, and of course the corresponding closing parenthesis and bracket. This is called a banana in the box, so let's see it in action!
<input [(ngModel)]="text">
<h2>{{ text }}</h2>
Y los enlaces equivalentes en WPF serían:
<TextBox Text="{Binding Path=Text, Mode=TwoWay}"></TextBox>
<TextBlock Text="{Binding Path=Text, Mode=OneWay}"></TextBlock>
The Angular binding is a matter of syntax, and in WPF it is more like a setup - in particular the value of Binding.Mode.
If we run this code, an error would occur in the console - saying that the ngModel is an unknown property of the input element. This is due to the fact, that in order to use the ngModel directive, it's necessary to import the FormsModule. It needs to be imported into the app.module.ts file:
import { FormsModule } from '@angular/forms';
...
@NgModule({
imports: [
BrowserModule,
FormsModule
]
...
If we run the sample, the initial input's value would be equal to default value, which is the text property's value. Since the input is editable, changing its value will reflect over the h2 element immediately. So typing into the input updates the text property, and then the h2 element displays that value via the interpolation.
Otra forma equivalente de lograr esto es:
<input [ngModel]="text" (ngModelChange)="text = $event">
En realidad, esto es similar al primer ejemplo, que usaba un enlace de propiedad y un enlace de evento.
Additional Resources
- Escritorio a Web: Escritorio a Web: Angular Enlace bidireccional con ngModel
- Encuadernación unidireccional en Angular
- Angular NgModel