O que é vinculação de dados bidirecional no Angular

    A vinculação de dados bidirecional no Angular permite que os dados fluam do componente para a exibição e vice-versa. Ele é usado para exibir informações para o usuário final e permite que ele faça alterações nos dados subjacentes usando a interface do usuário. Isso faz uma conexão bidirecional entre a visualização (o modelo) e a classe de componente que já mencionamos. O processo é semelhante à associação bidirecional no WPF.

    How does data binding work in Angular?

    Angular vinculação de dados funciona sincronizando os dados nos componentes angulares com a interface do usuário. Dessa forma, ele sempre pode mostrar o valor atual dos dados. Em termos de vinculação bidirecional, a sincronização automática de dados acontece entre o Model e a View, mantendo ambos sincronizados o tempo todo. Por causa disso, qualquer alteração feita no Modelo também é refletida imediatamente na Vista. E vice-versa – as alterações feitas na Vista também são atualizadas no Modelo. A associação de dados bidirecional no Angular é usada para exibir informações para o usuário final e permite que o usuário final faça alterações nos dados subjacentes usando a interface do usuário. Isso faz uma conexão bidirecional entre a exibição (o modelo) e a classe de componente. Isso é semelhante à associação bidirecional no WPF.

    Uma associação unidirecional está pegando o estado de nossa classe de componente e exibindo-o em nossa exibição. Vejamos 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

    Felizmente, podemos implementar a lógica da amostra acima de uma maneira muito mais fácil e é aqui que entra a ligação bidirecional!

    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>
    

    E as associações equivalentes no WPF seriam:

    <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.

    Outra maneira equivalente de conseguir isso é:

    <input [ngModel]="text" (ngModelChange)="text = $event">
    

    Na verdade, isso é semelhante ao primeiro exemplo, que usou uma associação de propriedade e uma associação de evento.

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.