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

问题描述 投票:0回答:1

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

为什么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" />
angular angular-directive
1个回答
1
投票

我在角度6中面临同样的问题,我能找到的唯一解决方案是使用像这样的skip(1)

    this.ngModel.valueChanges.pipe(skip(1)).subscribe((value) => {
        // your code here
    });
© www.soinside.com 2019 - 2024. All rights reserved.