我的工作我的Angular2项目。我公司开发的形式,我想使所有所需的字段。我试图让需要的标题,但它没有显示所需的输出。我没有得到什么走错了。请指引我正确的方向。
# product-form.component.html
<form #f="ngForm" (ngSubmit)="save(f.value)">
<div class="form-group">
<label for="title">Title</label>
<input #title="ngModel" ngModel name="title" id="title" type="text" class="form-control">
<div class="alert alert-danger" *ngIf="title.touched && title.invalid">
Title is required.
</div>
</div>
<div class="form-group mb-3">
<label for="price">Price</label>
<div class="input-group-prepend">
<span class="input-group-text">$</span>
<input ngModel name="price" id="price" type="number" class="form-control">
</div>
</div>
<div class="form-group">
<label for="category">Category</label>
<select ngModel name="category" id="category" class="form-control">
<option value=""></option>
<option *ngFor="let c of categories$ | async" [value]="c.$key">
{{ c.name }}
</option>
</select>
</div>
<div class="form-group">
<label for="imageUrl">image URL</label>
<input ngModel name="imageUrl" id="imageUrl" type="imageUrl" type="text" class="form-control">
</div>
<button class="btn btn-primary">Save</button>
</form>
据我所知只需添加需要这样的投入
product-form.component.html
<form #f="ngForm" (ngSubmit)="save(f.value)">
<div class="form-group">
<label for="title">Title</label>
<input required #title="ngModel" ngModel name="title" id="title" type="text" class="form-control">
<div class="alert alert-danger" *ngIf="title.touched && title.invalid">
Title is required.
</div>
</div>
<div class="form-group mb-3">
<label for="price">Price</label>
<div class="input-group-prepend">
<span class="input-group-text">$</span>
<input required ngModel name="price" id="price" type="number" class="form-control">
</div>
</div>
<div class="form-group">
<label for="category">Category</label>
<select ngModel name="category" id="category" class="form-control">
<option value=""></option>
<option *ngFor="let c of categories$ | async" [value]="c.$key">
{{ c.name }}
</option>
</select>
</div>
<div class="form-group">
<label for="imageUrl">image URL</label>
<input required ngModel name="imageUrl" id="imageUrl" type="imageUrl" type="text" class="form-control">
</div>
<button class="btn btn-primary">Save</button>
</form>
但我更喜欢使用反应形式。所以在你部件JavaScript文件创建一个表单
form: FormGroup;
constructor(formbuilder: FormBuilder){}
ngOnInIt(){
this.form = this.formbuilder.group({
title: new FormControl('', [validators.Required])
})
}
然后在模板不喜欢
product-form.component.html
<form [formGroup]="form" (ngSubmit)="save(f.value)">
<div class="form-group">
<label for="title">Title</label>
<input [formControlName]="title" id="title" type="text" class="form-control">
</div>
</form>
这种方式是更好的IMO
正如我在评论OP回答不得不使用HTML5 [要求]属性输入标签,以便将它们设置为需要。