简体   繁体   English

Angular 两种方式绑定不起作用[(NgModel)]

[英]Angular two way binding is not working [(NgModel)]

In angular code trying 2 way binding using model.在 angular 代码中尝试使用 model 进行 2 路绑定。 But encountered error message while loading the page.但是在加载页面时遇到错误消息。 ErrorMessage : Cannot read property 'username' of undefined at RegisterComponent_Template (register.component.html:6).错误消息:无法读取 RegisterComponent_Template 处未定义的属性“用户名”(register.component.html:6)。

register.html寄存器.html

      <form #registerForm="ngForm" (ngSubmit)="register()" autocomplete="off">
      <h2 class="text-center text-primary">SignUp</h2>
      <hr>
      <div class="form-group">
      <input type="text" class="form-control" name="username" 
      [(ngModel)]="model.username" placeholder="username">

       </div>
       <div class="form-group">
      <input type="text" class="form-control" name="password" [(ngModel)]="model.password" 
      placeholder="password">
      <p> You entered {{model.password}}</p>
     </div>

     <div class="form-group">
     <button class="btn btn-success mr-2" type="submit">Register</button>
     <button class="btn btn-default mr-2" type="button" (click)="cancel()">Cancel</button>
     </div>
    </form>

register.ts注册.ts

  import { Component, Input, OnInit, Output,EventEmitter } from '@angular/core';
import {FormsModule} from '@angular/forms';
import { AccountService } from '../_services/account.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
@Output () cancelRegister = new EventEmitter();
  constructor(private accountService: AccountService) { }
  model:any;

  ngOnInit(): void {

    
  }


  register() {
    this.accountService.register(this.model).subscribe(response => {
      console.log(response);
      this.cancel();
    }, error => {
      console.log(error);
    })
  }
  cancel() {
    this.cancelRegister.emit(false);
  }

}

The error is due to the ngForm variable model not being initialized.该错误是由于ngForm变量model未初始化所致。
In your ngOnInit try initializing it like在你的 ngOnInit 尝试初始化它

this.model = {  userName: '', password: '' };

You can change your model from model: any with:您可以将 model 从model: any更改为:

model: {
  username: string;
  password: string;
} = {
  username: '',
  password: ''
};

And now, you can try again.现在,您可以再试一次。

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

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