Created
September 2, 2017 07:10
-
-
Save Feng-JY/2aaecf5d613d8d1f6a93afd9207d17e8 to your computer and use it in GitHub Desktop.
NG 表单基础类
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { FormBuilder } from '@angular/forms'; | |
/** | |
* 表单基础类 | |
* | |
* @export | |
* @class FormComponent | |
*/ | |
export class FormComponent { | |
form: any; //表单 | |
submitted = false; //是否提交 | |
fb: FormBuilder = new FormBuilder(); //ng Form | |
constructor() { } | |
/** | |
* 构建表单 | |
* | |
* @param {*} controls | |
* @memberof FormComponent | |
*/ | |
buildForm(controls: any) { | |
this.form = this.fb.group(controls); | |
} | |
/** | |
* 重置表单 | |
* | |
* @memberof FormComponent | |
*/ | |
resetForm() { | |
this.form.reset(); | |
for (const i in this.form.controls) { | |
this.form.controls[i].markAsPristine(); | |
} | |
this.submitted = false; | |
} | |
/** | |
* 提交表单 | |
* | |
* @memberof FormComponent | |
*/ | |
submitForm(doSubmit: Function) { | |
for (const i in this.form.controls) { | |
this.form.controls[i].markAsDirty(); | |
} | |
if (this.form.valid) { | |
this.submitted = true; | |
doSubmit(); | |
} | |
} | |
/** | |
* 获取表单control对象 | |
* | |
* @param {any} name | |
* @returns | |
* @memberof ChangePwdComponent | |
*/ | |
getFormControl(name: string) { | |
return this.form.controls[name]; | |
} | |
/** | |
* 表单错误 | |
* | |
* @param {string} name | |
* @param {(string | Array<string>)} errors | |
* @memberof FormComponent | |
*/ | |
hasErrors(name: string, errors: string | Array<string>) { | |
let control = this.getFormControl(name); | |
let error = false; | |
// TODO: 多个error处理 ['required','ip'] | |
if(errors && typeof errors === 'string') { | |
error = control.hasError(errors); | |
} | |
return control.dirty && error; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment