首页 > 解决方案 > 无法在应用指令的情况下更改 ngOnInit 中的 dom 元素值

问题描述

我正在使用自定义指令来格式化百分比值。一切都按预期工作,除了我无法加载我在 ngOnInit 上应用指令的元素的格式化值。如果该元素上没有 [(ngModel)] 它工作正常。我也尝试过使用其他生命周期钩子,例如 ngAfterViewInit,但它不起作用。它适用于 ngAfterViewChecked 或 ngDoCheck,但是在输入元素中输入值时指令行为不正确。

请参考示例百分比指令

<!-- in app.component.html -->
<input type="text" appPercent [digit]="3" [decimals]="2" 
  [(ngModel)]="profitPercent">
// in percent.directive.ts
ngOnInit(){
    let decimalZeroes = "0".repeat(this.decimals);
    let uiValue: string = `0.${decimalZeroes}`;
    let onBlurValue: string = this.el.nativeElement.value;
    let parsedValue: number =  parseFloat(onBlurValue);

    if (parsedValue>100.0) {
      uiValue = `100.${decimalZeroes}`;
    } else if(!isNaN(parsedValue)){
      // this.model.update.emit(parsedValue); // this does not work
      uiValue = this.decimalPipe.transform(parsedValue,'1.'+ this.decimals + '-' + this.decimals);
    }
    this.el.nativeElement.value = uiValue + '%';
}

标签: angularangular-directive

解决方案


我通过以下步骤修复了它:

  • 移除 NgModel 作为提供者
  • 从构造函数中删除 NgModel 以使 NgControl 受益
  • 在 valueChanges 的订阅中移动了 onInit 逻辑
constructor(control: NgControl) {}

ngOnInit(){
    this.control.valueChanges.subscribe(value => {
      let decimalZeroes = "0".repeat(this.decimals);
      let uiValue: string = `0.${decimalZeroes}`;
      let onBlurValue: string = this.el.nativeElement.value;
      let parsedValue: number =  parseFloat(onBlurValue);

      if (parsedValue>100.0) {
        uiValue = `100.${decimalZeroes}`;
      } else if(!isNaN(parsedValue)) {
        uiValue = this.decimalPipe.transform(parsedValue,'1.'+ this.decimals + '-' + this.decimals);
      }
      this.el.nativeElement.value = uiValue + '%';
    });
  }


推荐阅读