我正在从官方指南中学习Angular2。我已经创建了一个CRUD应用程序,就功能而言,一切都运行得很好。我想要的一件事是能够使用[(ngModel)]并且在初始加载表单时仍然有空白表单字段。目前,为了使ngModel正常工作,我使用模型的硬编码值初始化了表单。这是我的设置:
组件:
@Component({
selector:'create-form',
templateUrl: './app/createTemplate.html'
})
export class CreateComponent{
model = new DemoBean(123321, 1,'test',1.3); //TODO - initialize blank form fields for these values.
http:Http;
constructor(http:Http){ //Dependency injection of Http.
this.http = http;
}
msg:string;
onSubmit(id: number, str: string, num: number, d: number) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.model = new DemoBean(id,num,str,d);
this.http.post('http://localhost:8080/create', JSON.stringify(this.model),{headers:headers}).map((res) => res.text())
.subscribe(msg => this.msg = msg);
}
}
表单模板:
<div class="container">
<form (ngSubmit) = "onSubmit(id.value, str.value, num.value, d.value)" #demoForm="ngForm">
<div class="form-group">
<label for="long_id">long Id</label>
<input type="text" class="form-control" [(ngModel)]="model.id" #id required>
</div>
<div class="form-group">
<label for="string_str">String str</label>
<input type="text" class="form-control" [(ngModel)]="model.str" #str required>
</div>
<div class="form-group">
<label for="int_num">int num</label>
<input type="text" class="form-control" [(ngModel)]="model.num" #num required>
</div>
<div class="form-group">
<label for="double_d">double d</label>
<input type="text" class="form-control" [(ngModel)]="model.d" #d required>
</div>
<button type="submit" class="btn btn-default" [disabled]="!demoForm.form.valid">Submit</button>
<div><p>{{msg}}</p></div>
</form>
</div>
任何建议都会有很大的帮助。
答案 0 :(得分:1)
只传递一个空值
model = new DemoBean('', '','','');
答案 1 :(得分:0)
我使用这种方法并且很好
我的模特:
export class model {
constructor(
public id: number,
public title: string,
public description: string
) { }
static readonly EMPTY_MODEL = {
id: 0,
title: '',
description: ''
};
}
初始化空白:
mdl: model = model.EMPTY_MODEL;
,无需new()
表达。