在角度代码中尝试使用模型进行 2 路绑定。但是在加载页面时遇到错误消息。 错误消息:无法读取 RegisterComponent_Template (register.component.html:6) 处未定义的属性“用户名”。
注册.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>
注册.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);
}
}
答案 0 :(得分:1)
错误是由于未初始化 ngForm
变量 model
。
在你的 ngOnInit 尝试初始化它像
this.model = { userName: '', password: '' };
答案 1 :(得分:0)
您可以通过以下方式从 model: any
更改您的模型:
model: {
username: string;
password: string;
} = {
username: '',
password: ''
};
现在,您可以再试一次。