0

I try to know the value of an input within the function, but when I try to call the next line in the function "validateAllFormFields()":

 if (this.txtImporteMaximoVC==="0") 

"this" is "undefined"

what I want is to retrieve the control value of "txtImporteMaximoVC", but if I try to recover the value from the formcontrol with control.value, it always returns empty and the input really has values, I think that control.value ="" because de formControl is using a directive.

the component.ts:

        import { Component, HostBinding, OnDestroy, OnInit, Input, Output, EventEmitter, ElementRef, NgModule, ViewChild, ChangeDetectorRef  } from '@angular/core';
import { Validators, FormBuilder, FormControl, FormGroup, AbstractControl,  ValidatorFn } from '@angular/forms';
import { AfterViewChecked } from '@angular/core/src/metadata/lifecycle_hooks';
import { CustomValidators } from '../../../shared/customValidators/custom.validators';
import { CurrencyPipe } from "../../../shared/pipes/pipeFormatCurrency/currency.pipe";
import { FieldErrorDisplayComponent } from '../../../shared/comun/fieldErrorDisplay/field-error-display.component'
import { FocusDirective } from '../../../shared/directives/focus.directive';

@Component({
    selector: 'app-formulario-contrato',
    templateUrl: './contrato.component.html',
    styleUrls: ['./contrato.component.css'],
    providers: [CurrencyPipe],

})
export class FormularioContratoComponent  {

    @Output() pressPointDecimal: boolean;
    @Output() setFormat: boolean;
    @ViewChild('txtImporteMaximo') txtImporteMaximoVC;
    //__________________________________________________ Validaciones formulario:


    constructor(private elRef: ElementRef, private formBuilder: FormBuilder, private cdRef: ChangeDetectorRef, private formatcurrencypipe: CurrencyPipe) {      

        this.createForm();  
    }

    public txtImporteMaximo = new FormControl('', [this.lessThanZeroValidator]);  

    createForm() {
        this.contratoForm = this.formBuilder.group({     
            txtImporteMaximo: this.txtImporteMaximo,
        });
    }

    lessThanZeroValidator(fieldControl: FormControl) {     
        if (fieldControl && fieldControl.value != null && !isNaN(parseInt(fieldControl.value)) && fieldControl.value <= 0) {        
            return { lessThanZeroErr: true };
        }
        else {           
            return null;
        }
    }    

    isFieldInvalid(field: string) {   
        if (this.contratoForm && this.contratoForm.get(field)) {          
            return !this.contratoForm.get(field).valid && this.contratoForm.get(field).touched;

        } else {
            if (this.contratoForm && this.contratoForm.controls["fechas2"].get(field)) {              
                return !this.contratoForm.controls["fechas2"].get(field).valid && this.contratoForm.controls["fechas2"].get(field).touched;
            }
        } // if (this.contratoForm && this.contratoForm.get(field)) {

        return null;     
    }

    ngAfterViewChecked() {
        this.cdRef.detectChanges();
    }

    limpiar() {          
        this.contratoForm.reset();      
    }    

    onClick() {
        this.validateAllFormFields(this.contratoForm);      
    }

    onCloseLink() {
        if (this.closeFunction) {
            this.closeFunction();
        }
    }

    validateAllFormFields(formGroup: FormGroup) {        
        Object.keys(formGroup.controls).forEach(field => { 
            const control = formGroup.get(field);            
            if (control instanceof FormControl)
            {  
                if (field == "txtImporteMaximo") {

                    if (this.txtImporteMaximoVC === "0") {
                        control.setErrors({ lessThanZeroErr: true });
                    }
                }
                control.markAsTouched({ onlySelf: true });
            } else if (control instanceof FormGroup) {       
                this.validateAllFormFields(control);           
            }
        });
    }

}

component.html:

<div>
    <form [formGroup]="contratoForm" #form="ngForm">
        <div class="content">
            <div class="form-group">
                <div class="control">
                    <label class="etiquetaFormulario" for="txtImporteMaximo">Importe Máximo</label>
                    <input autocomplete="off" [formControl]="txtImporteMaximo" type="text" id="txtImporteMaximo" name="txtImporteMaximo" class="cajaTexto ancho80" currencyFormatterDirective [pressPointDecimal]="true" [setFormat]="true" />
                </div>
                <div *ngIf="txtImporteMaximo.hasError('lessThanZeroErr')">
                    <app-field-error-display [displayError]="'true'" [errorMsg]="'El importe debe ser mayor que cero'"></app-field-error-display>
                </div>
                <div *ngIf="isFieldInvalid('txtImporteMaximo') && !txtImporteMaximo.hasError('lessThanZeroErr')">
                    <app-field-error-display [displayError]="'true'" [errorMsg]="'Por favor, informe el campo importe máximo'"></app-field-error-display>
                </div>  
            </div>
            <div class="linea"></div>         
        </div>
        <div class="footer">
            <div class="buttons">
                <button class="btn btn-primary boton" type="button" style="float:right;" (click)="onCloseLink()">
                    <span class="glyphicon glyphicon-off"></span> Cancelar
                </button>

                <button class="btn btn-primary boton" type="button" style="float:right;" (click)="limpiar()">
                    <span class="glyphicon glyphicon-trash"></span> Limpiar
                </button>
                <button type="submit" [disabled]="!contratoForm.valid" class="btn btn-primary boton" style="float:right;" (click)="onClick()">
                    <span class="glyphicon glyphicon-floppy-disk"></span> Guardar
                </button>
            </div>
            <div class="clear" style="clear:both;"></div>
        </div>    
    </form>
    <div class="clear" style="clear:both;"></div>
</div>

Any idea?

ararb78
  • 1,137
  • 5
  • 19
  • 44
  • What do you want to do? Your code makes no sense. A `ViewChild` Reference is of type `ElementRef`, not a primitive value. – malifa Jan 09 '18 at 13:49
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Estus Flask Jan 09 '18 at 14:02

1 Answers1

2

Who calls validateAllFormFields method? There may be cases where execution context may not be defined... You may try to bind Component's this to that method explicitly on the Component's constructor:

this.validateAllFormFields = this.validateAllFormFields.bind(this);
dhilt
  • 18,707
  • 8
  • 70
  • 85