我使用Angular cli来提交一个简单的表单,但是,输入元素中的必需属性不起作用,我仍然可以在不输入任何内容的情况下提交表单,即使它们包含在表单元素中。我用Google搜索了解决方案,但不知怎的,我还是无法弄明白。提前谢谢。
这是html代码:
<form (submit)="onAddSubmit()">
<div class="form-group">
<label>Title</label>
<input class="form-control" type="text" [(ngModel)]="title" name="title" required>
</div>
<div class="form-group">
<label>City</label>
<input class="form-control" type="text" [(ngModel)]="city" name="city" required>
</div>
<div class="form-group">
<label>Owner</label>
<input class="form-control" type="text" [(ngModel)]="owner" name="owner" required>
</div>
<div class="form-group">
<label>Bedrooms</label>
<input class="form-control" type="number" [(ngModel)]="bedrooms" name="bedrooms" required>
</div>
<div class="form-group">
<label>Type</label>
<select class="form-control" type="text" [(ngModel)]="type" name="type" required>
<option value="Estate">Estate</option>
<option value="Condo">Condo</option>
<option value="Apartment">Apartment</option>
</select>
</div>
<div class="form-group">
<input id="image" name="image" [(ngModel)]="image" type="file" >
</div>
<div class="form-group">
<label>Price</label>
<input class="form-control" type="text" [(ngModel)]="price" name="price" required>
</div>
<input type="submit" value="Submit" class="btn btn-success">
</form>
答案 0 :(得分:0)
使用角度的反应形式来实现验证。请参考以下示例。
import {
FormBuilder,
FormGroup,
Validators
} from '@angular/forms';
export class AppComponent implements OnInit {
registerForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required]
});
}
}
Html template
<form [formGroup]="registerForm">
<label>Firstname:</label>
<input type="text" formControlName="firstname">
<p *ngIf="registerForm.controls.firstname.errors">This field is required!</p>
<label>Lastname:</label>
<input type="text" formControlName="lastname">
<p *ngIf="registerForm.controls.lastname.errors">This field is required!</p>
</form>