我有一个指令观察组件更改,并在更改值时调用自定义验证器。
为什么ngModel.valueChanges在初始化组件时有新的变化?
@Directive({
providers: [NgModel],
selector: "[inputValidator][ngModel]",
})
@Inject(BootstrapFormGroupComponent)
export class InputValidatorDirective implements OnInit, BootstrapFormGroupMember {
public ngOnInit() {
this.ngModel.valueChanges.subscribe((value) => {
// ...
// calling custom validators
// why it is called after the component has initialized
// ...
});
}
}
HTML:
<input type="number" inputValidator [validator]="postalCodeValidator" [(ngModel)]="postalCode" class="form-control" />
答案 0 :(得分:1)
我在第6个角度遇到了同样的问题,我唯一能找到的解决办法就是像这样使用skip(1)
this.ngModel.valueChanges.pipe(skip(1)).subscribe((value) => {
// your code here
});