Angular 2(十): 指令

生成指令命令行:ng g directive directiveName

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Directive } from "@angular/core";
import { mobileValidator } from '../validators';
@Directive({
selector:'[ mobile ]',
providers:[
{
provide: NG_VALIDATORS,
useValue:mobileValidator,
//设置该字段,表示一个token下面可以挂载多个指令
multi:true
}
]
})
export class MobileValidatorDirective implements Init{
constructor(){}
}
1
<input type="text" #mobile="ngModel" ngModel name="mobile" (input)="onMobileInput(myForm)"/>
1
2
3
4
5
6
7
8
9
10
mobileValid:boolean = true;
mobileUntouched:boolean = true;
onMobileInput(formData:NgForm){
if(formData){
//用这两个值来控制错误信息的显示和隐藏
this.mobileValid = formData.form.get('mobile').valid;
this.mobileUntouched = formData.form.get('mobile').untouched;
}
}