I have the template like below:
<form [formGroup]="configWeightage">
<div >
Enter value in between 0 to 100 <mat-form-field>
<input
matInput
type="number"
min="0"
max="100"
[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>
This is the class file
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
}
)
}
}
I am supposed the fire the error when there is a value NOT in between 0 and 100
But no validation message will be fired
Here is the stack bliz code for the same, so that you can run and fix yourself.
CodePudding user response:
There are some errors and typos you should fix in your Stackblitz :
Remove brackets from
[formControlName]
Remove
min
andmax
attributes from<input>
as you've already specified them usingvalidators
Move
<mat-error>
inside<mat-form-field>
For the error condition, you should use
formGroupName.get('FormControlName').hasError('validatorName')
Remove
style="color: red"
from<mat-error>
, this is already the default style for the error message.Fix the typo
this.formBuilder.group
to bethis.fb.group
Here is Stackblitz after fixing the above errors.