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?