简体   繁体   English

ngModel 两种方式绑定在 Angular 中不起作用

[英]ngModel Two way binding not working in Angular

<input matInput placeholder="username" [(ngModel)]="userId">
<input matInput placeholder="name" [(ngModel)]="name">

I have also imported the FormsModule我还导入了 FormsModule

import { FormsModule } from '@angular/forms'

@NgModule({
  declarations: [
    AppComponent,
    UserInputComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-user-input',
  templateUrl: './user-input.component.html',
  styleUrls: ['./user-input.component.css']
})

export class UserInputComponent implements OnInit {

 userId: string = 'userId';
 name: string = 'name';
  constructor() { }

  ngOnInit(): void {
  }

  
  }
}

The initial values are getting printed in the console but when a new value is entered, the variables userId and name don't get updated.初始值正在控制台中打印,但是当输入新值时,变量 userId 和 name 不会更新。 if I don't give an initial value to userId and name then printing them on the console gives me undefined even after entering them from the input.如果我没有为 userId 和 name 提供初始值,那么即使在从输入中输入它们之后,在控制台上打印它们也会给我 undefined 。 Kindly help me figure out what's the issue.请帮我找出问题所在。

EDIT The problem was fixed by including a name attribute in the input tag.编辑通过在输入标签中包含名称属性来解决问题。

Your are not posted full code.你没有发布完整的代码。 But anyhow I add button and click event.但无论如何我添加按钮和点击事件。 Now when you click you need to update model then it will update values.现在,当您单击时,您需要更新 model 然后它将更新值。 Currently you assigned first time but when click your not assign new value to inputs当前您是第一次分配,但是当单击时您没有为输入分配新值

<input matInput placeholder="username" [(ngModel)]="userId">
    <input matInput placeholder="name" [(ngModel)]="name">
    <button (click)="test(event)" value="click"/>



import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-user-input',
  templateUrl: './user-input.component.html',
  styleUrls: ['./user-input.component.css']
})

export class UserInputComponent implements OnInit {

 userId: string = 'userId';
 name: string = 'name';
  constructor() { }

  ngOnInit(): void {
  }

test(e){
userId=e.target.value;
name=e.target.value;
}

  
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM