我正在从事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>
答案 0 :(得分:0)
afaik只需将必需项添加到这样的输入中
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
答案 1 :(得分:0)
正如我在评论中回答的那样,OP必须使用HTML5 [required]属性输入标签,以便根据需要设置标签。