我是angular2的新手,我想在用户在dropDown中选择某个值时触发一个函数。因此,我尝试实现FormControl类的statusChange,但未触发它,
想知道如何以及何时在angular2中使用statusChange这是我的代码
class policy{
subCategory: FormControl = new FormControl();
ngOnInit() {
this.subCategory.statusChanges.subscribe(
s => {
alert('success');
}, e => {
alert('error');
}, () => {
alert('complete');
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为通过实现statusChanges,我可以在下拉列表中的每个值更改上触发成功函数,显然现在它可以正常工作。
更新1
我已经更新了plunkr
如评论所述,您可能想要valueChanges替代。但是,对于成千上万的人通过搜索工作方式来到这里statusChanges,您可以:
this.subCategory.statusChanges.subscribe( (status) => {
console.log(status); //status will be "VALID", "INVALID", "PENDING" or "DISABLED"
})
Run Code Online (Sandbox Code Playgroud)
该文档描述了这四个可能的值,如下所示:
- 有效:此控件已通过所有验证检查。
- 无效:此控件未通过至少一项验证检查。
- 待审核:此控件正在执行验证检查。
- 禁用:此控件免于验证检查。这些状态值是互斥的,因此控件不能同时是有效和无效的,也不能是无效和禁用的。
在 Reactive 形式中valueChanges,statusChanges两者看起来非常相似,但有两个不同的目的。
statusChanges是AbstractControl每次重新计算控件的验证状态时发出事件的属性。其他答案中解释的状态很少
valueChanges是AbstractControl每次使用 UI 或以编程方式更改控件值时发出事件的属性。
提示:属性AbstractControl意味着您可以将这些事件附加到FormControl,FormArray或FormGroup
示例:component.html
<form [formGroup]="form">
<h2 class="text-center">Registration Form</h2>
<br>
<div class="form-group">
<input type="text" class="form-control" placeholder="first Name" formControlName="firstName">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="last Name" formControlName="lastName">
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="email" formControlName="email">
<span *ngIf="form.controls['email']?.errors?.required">This field is required</span>
</div>
<br>
<div *ngIf="form.valid">
Valid form
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
组件.ts
ngOnInit() {
this.form = this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
email: ['', Validators.required],
});
this.form.valueChanges.subscribe((value) => {
console.log('valueChanges Form value ' + value);
});
this.form.statusChanges.subscribe((status) => {
console.log('statusChanges Status is ' + status);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5058 次 |
| 最近记录: |