Tengo la plantilla como a continuación:
<form class="form" [formGroup]="configWeightage"> <div class="example-container"> Enter value in between 0 to 100 <mat-form-field> <input matInput type="number" min="0" max="100" class="example-right-align" [formControlName]="weightageValue" id="weightage" required /> </mat-form-field> <mat-error *ngIf="weightageValue.hasError('min(0)')" style="color: red" >Please enter greater than 0</mat-error > <mat-error *ngIf="weightageValue.hasError('max(100)')" style="color: red" >Please enter less than 100</mat-error > </div> </form>Este es el archivo de clase.
import { Component } from '@angular/core'; import { FormBuilder,FormGroup, Validators,FormControl } from '@angular/forms'; /** @title Form field with prefix & suffix */ @Component({ selector: 'form-field-prefix-suffix-example', templateUrl: 'form-field-prefix-suffix-example.html', styleUrls: ['form-field-prefix-suffix-example.css'], }) export class FormFieldPrefixSuffixExample { configWeightage:FormGroup; formBuilder : FormBuilder; weightageValueControl = new FormControl(['',Validators.required,Validators.min(0),Validators.max(100)]); hide = true; constructor(private fb: FormBuilder) {} ngOnInit() { this.configWeightage = this.formBuilder.group( { 'weightageValue' :this.weightageValueControl } ) } }Se supone que se dispara el error cuando NO hay un valor entre 0 y 100
Pero no se disparará ningún mensaje de validación.
Aquí está el código de stack bliz para el mismo, para que pueda ejecutarlo y arreglarlo usted mismo.
Hay algunos errores y errores tipográficos que debe corregir en su Stackblitz:
Eliminar corchetes de [formControlName]
Elimine los atributos min y max de <input> como ya los especificó usando validators
Mover <mat-error> dentro <mat-form-field>
Para la condición de error, debe usar formGroupName.get('FormControlName').hasError('validatorName')
Elimine style="color: red" de <mat-error> , este ya es el estilo predeterminado para el mensaje de error.
Corrija el error tipográfico this.formBuilder.group para que sea this.fb.group
Aquí está Stackblitz después de corregir los errores anteriores.