如何在输入数字字段中正确传递更改以触发ngModel?

时间:2019-04-08 22:11:48

标签: angular typescript

我有一个打开对话框的按钮(MatDialog)。该对话框允许用户选择时钟面上的值。我执行了一个返回数字的计算。当用户关闭对话框时,数字将返回到原始父级并更新数字输入字段。此输入字段用于计算视图上的另一个字段。当我单击上/下箭头时,计算所得的字段会更新。当我从对话框更新值时,不会触发计算。我想知道是否是因为它在Angular Zone之外?

我尝试使用jQuery中的触发事件。我还尝试了NgModelChange和Directives的实现。我以为使用指令可能是可行的方法,但我不确定我是否正确执行了指令。

// Dialog box code that runs when the end user clicks the close button
// calcHours function to calculate the hours worked when the clock dialog is used
  public calcHours (): void {
    // Variables to capture timeClock entries from DOM. Total variable to house calculation
    let currentStartTime = this.elStartTime.nativeElement.value;
    let currentStopTime = this.elStopTime.nativeElement.value;
    // Cast the returned time from string to number
    currentStartTime = +( currentStartTime.slice( 0, -( currentStartTime.indexOf( ':' ) + 1 ) ) );
    currentStopTime = +( currentStopTime.slice( 0, -( currentStopTime.indexOf( ':' ) + 1 ) ) );
    // Math to calculate the number of hours based upon the returned string time
    const totalHours = currentStopTime - currentStartTime;
    if ( currentStartTime !== '' && currentStopTime !== '' ) {
      this.dialogRef.close( totalHours );
    }
  }
// Parent code that runs after the dialog is closed
dialogRef.afterClosed().subscribe( result => {
      // Value returned from dialog box
      const dialogHoursCalc = `${ result }`;
      // Set value of input field from dialog box
      // this.renderer.setProperty( this.elHoursWorked.nativeElement, 'value', dialogHoursCalc );
      // Tried using jQuery instead of renderer
      $( '#hoursWorked' ).val( dialogHoursCalc );
      $( '#hoursWorked' ).trigger( 'change' );
    } );
// Pay field that is calculated using the hours from the hoursWorked field
<input type="number" class="form-control" data-number-to-fixed="2" [(ngModel)]="timecarddet.earnings" readonly="true" id="c2" disabled>
/// Directive
import { Directive, OnInit, EventEmitter, Output, ElementRef, NgZone } from '@angular/core';

@Directive({ selector: '[appHoursWorked]' })

export class HoursWorkedDirective implements OnInit {
  @Output() ngModelChange: EventEmitter<any> = new EventEmitter(false);

  constructor(
    private _el: ElementRef,
    private _ngZone: NgZone
  ) { }

  ngOnInit(){
    this._ngZone.run(() =>
    this.ngModelChange.emit(this._el.nativeElement.value));
  }
}

我希望用对话框中的计算来更改数字输入字段,然后以与有人直接手动更新该字段相同的方式执行工资计算。

EDIT 这是我尝试过的指令路线...

{{1}}

我将选择器作为输入的属性。我将指令导入了app模块并声明了该指令。当我这样做时,我收到以下错误信息……

错误错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。

0 个答案:

没有答案