为何在Angular 4 @Directive中初始化组件时调用ngModel.valueChanges

时间:2017-11-02 12:44:29

标签: angular angular-directive

我有一个指令观察组件更改,并在更改值时调用自定义验证器。

为什么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" />

1 个答案:

答案 0 :(得分:1)

我在第6个角度遇到了同样的问题,我唯一能找到的解决办法就是像这样使用skip(1)

    this.ngModel.valueChanges.pipe(skip(1)).subscribe((value) => {
        // your code here
    });