我正在研究角度7,并遵循form.component.html代码:
{{userForm.value | json}}
{{userModel | json}}<div class="form-group"> <label>Name</label> <input type="text" class="form-control" name="userName" [(ngModel)]="userModel.userName"> </div> <div class="form-group"> <label>Email</label> <input type="text" class="form-control" name="email" [(ngModel)]="userModel.email"> </div> <div class="form-group"> <label>Mobile number</label> <input type="number" class="form-control" name="number" [(ngModel)]="userModel.number"> </div> <div class="form-group"> <label>Address</label> <input type="text" class="form-control" name="address" [(ngModel)]="userModel.address"> </div> <button class="btn btn-primary" type="submit">Submit Order</button>
user.js代码
export class User {
constructor(
public userName: string,
public email: string,
public number: string,
public address: string
){}
}
app.component.ts:
import { Component } from '@angular/core';
import { User } from './User';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title=['Angular','Vue','React'];
userModel = new User('ash','ash@gmail.com','01233','asasas');
}
当我编译时,我得到未定义的错误“ userName”。
答案 0 :(得分:1)
<input formControlName="userName" placeholder="Name" class="form-control">
在每个输入字段中使用它,它将起作用。
答案 1 :(得分:1)
按如下所示更改您的User类
export class User {
public userName: string;
public email: string;
public number: string;
public address: string;
constructor(userName, email, number, address){
this.userName = userName;
this.email = email;
this.number = number;
this.address = address;
}
}
在这里查看有关typescript classes.
的更多信息@Hameed Syed再次对您的类导入语句进行了交叉检查。
已更新
您的代码对我来说似乎还不错,无论如何尝试使用Angular的生命周期方法进行数据绑定。
import { Component, OnInit } from '@angular/core';
import { User } from './User';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title=['Angular','Vue','React'];
userModel: User;
ngOnInit(){
this.userModel = new User('ash','ash@gmail.com','01233','asasas');
}
}