【问题标题】:Why ngModel.valueChanges called when component is initialized in Angular 4 @Directive为什么在Angular 4 @Directive中初始化组件时调用ngModel.valueChanges
【发布时间】:2017-11-02 12:44:28
【问题描述】:

我有一个指令来监视组件的变化,并在值发生变化时调用自定义验证器。

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

【问题讨论】:

  • 你如何使用它?显示html
  • postalCode的初始值是多少?
  • 我尝试过使用 null、undefined 和 ""

标签: angular angular-directive


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多