How do I make Angular Two Way Binding working here?

36 Views Asked by At

Can you help me to make it works, please?
The two-way binding is not getting/updating the values.
I would like that the values in app.component.ts were shown in app.component.html. Thanks!

I will post the files:

app.component.html:

<div>
  <form>
    <button type="button">Enviar</button><br>
    <label for="txt_usuario">Usuario:</label>
    <input type="text" id="txt_usuario" title="Usuário" size="10" [(ngModel)]="usuario"><br>
    <label for="txt_senha">Senha:</label>
    <input type="text" id="txt_senha" title="Senha" size="10" [(ngModel)]="senha"><br>
  </form>
  <span>Usuario: {{usuario}}</span><br>
  <span>Senha  : {{senha}}</span>
</div>

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  title: string = 'teste';
  usuario: string = 'X';
  senha: string = '123';

  send(usuario: string, senha: string) {
    console.log(usuario);
    console.log(senha);
  }
}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
2

There are 2 best solutions below

1
Roberto Yoc On

As you are using it inside a form you can use formsModule for the two way data binding

<form #f="ngForm">
   <button type="button">Enviar</button><br>
   <label for="txt_usuario">Usuario:</label><br>
   <input type="text" id="txt_usuario" title="Usuario" size="10" name="usuario" ngModel #usuario="ngModel" ><br>
   <label for="txt_senha">Senha:</label>
   <input type="text" id="txt_senha" title="Senha" size="10" name="seha" ngModel #senha="ngModel"><br>
</form>

or if you want to make them standalone:

<input [(ngModel)]="name" #ctrl="ngModel" required><br>
<span>Other: {{ctrl.value}}</span>

I added a project so you can see this working: https://stackblitz.com/edit/angular-zdtdww?file=src%2Fmain.ts

1
Fernando Lima On

I found that was missing name="usuario" and name="senha" in the inputs, like below:

<div>
  <form>
    <button type="button">Enviar</button><br>
    <label for="txt_usuario">Usuario:</label>
    <input type="text" id="txt_usuario" title="Usuário" size="10" name="usuario" [(ngModel)]="usuario"><br>
    <label for="txt_senha">Senha:</label>
    <input type="text" id="txt_senha" title="Senha" size="10" name="senha" [(ngModel)]="senha"><br>
  </form>
  <span>Usuario: {{usuario}}</span><br>
  <span>Senha  : {{senha}}</span>
</div>

Doing this change started to work.
Thanks Roberto, looking your answer I found this missing definition.