1.商品类别
getAllCategories(): string[] {
return ['电子产品', '硬件设备', '图书'];
}
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {ProductService} from '../shared/product.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
/*建数据模型*/
formModel: FormGroup;
categories: string[];
constructor(private productService: ProductService, fb: FormBuilder) {
fb = new FormBuilder();
this.formModel = fb.group({
title: ['', Validators.minLength(3)],
price: [null, this.positiveNumberValidator],
category: ['-1']
});
}
ngOnInit() {
this.categories = this.productService.getAllCategories();
}
/*正数校验器---》商品价格搜索框*/
positiveNumberValidator(control: FormControl): any {
if (!control.value) {
return null;
}
const price = parseInt (control.value, 10);
if (price > 0) {
return null;
} else {
return { positiveNumber: true};
}
}
onSearch() {
if (this.formModel.valid) {
console.log(this.formModel.value);
}
}
}
<!--数据模型与模板连接起来-->
<form [formGroup]="formModel" (ngSubmit)="onSearch()" novalidate>
<div class="form-group" [class.has-error]="formModel.hasError('minlength','title')">
<label for="productTitle">商品名称</label>
<input formControlName="title" type="text" id="productTitle" placeholder="商品名称"
class="form-control">
<!--展示错误信息-->
<span class="help-block" [class.hidden]="!formModel.hasError('minlength','title')">
请至少输入三个字
</span>
</div>
<div class="form-group" [class.has-error]="formModel.hasError('positiveNumber','price')">
<label for="productPrice">商品价格</label>
<input formControlName="price" type="text" id="productPrice" placeholder="商品价格"
class="form-control">
<!--展示错误信息-->
<span class="help-block" [class.hidden]="!formModel.hasError('positiveNumber','price')">
请输入整数
</span>
</div>
<div class="form-group">
<label for="productCategory">商品类别</label>
<select formControlName="category" id="productCategory" class="form-control">
<option value="-1">请选择</option>
<option *ngFor="let category of categories" [value]="category">{{category}}</option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">搜索</button>
</div>
</form>