Angular 4 'this' не определено

Я пытаюсь узнать значение ввода внутри функции, но когда я пытаюсь вызвать следующую строку в функции «validateAllFormFields ()»:

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

"это" - "не определено"

я хочу получить контрольное значение "txtImporteMaximoVC", но если я попытаюсь восстановить значение из formcontrol с помощью control.value, оно всегда будет пустым, а ввод действительно имеет значения, я думаю, что control.value = "" потому что de formControl использует директиву.

компонент 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>

Любая идея?


person ararb78    schedule 09.01.2018    source источник
comment
Что ты хочешь делать? Ваш код не имеет смысла. ViewChild Ссылка имеет тип ElementRef, а не примитивное значение.   -  person lexith    schedule 09.01.2018
comment
Возможный дубликат Как получить доступ к правильному `this` внутри обратного вызова ?   -  person Estus Flask    schedule 09.01.2018


Ответы (1)


Кто вызывает validateAllFormFields метод? Могут быть случаи, когда контекст выполнения не может быть определен ... Вы можете попытаться привязать this Компонента к этому методу явно в конструкторе Компонента:

this.validateAllFormFields = this.validateAllFormFields.bind(this);
person dhilt    schedule 09.01.2018