Iam facing the issue that mat-form-field required asterik even if there is no error. I would like to show blue asterik if there is no error. I have spent a lot of time but I am not able to fogure it out. If anyone knows what is wrong then please let me know. Thank you
<mat-form-field appearance="outline" matInput>
<mat-label>Name</mat-label>
<input
(input)="onNameChange()"
formControlName="name"
type="text"
autocomplete="off"
matInput
maxlength="50"
required="required"
/>
<mat-icon
*ngIf="form.hasError('required', 'name') && isNameSubmitted"
matSuffix
>
</mat-icon>
<mat-error *ngIf="form.hasError('required', 'name') && isNameSubmitted">
<span>{{ "This field is mandatory" | translate }}</span>
</mat-error>
<mat-error *ngIf="form.hasError('maxlength', 'name') && isNameSubmitted">
<span>{{ "Maximum 50 charachers are allowed" | translate }}</span>
</mat-error>
</mat-form-field>
CodePudding user response:
Since you're using a form field with formControlName
directive i guess you have a formGroup, if you just want to make sure the input has a value don't use required
directly on the template, instead use Validators
in the .ts file of your component.
For example:
public myFormGroup: FormGroup = new FormGroup({
name: new FormControl('', Validators.required)
})
In the FormControl constructor you can pass, as the second parameter, a validator function or an array of validator functions. The required function is one of them, addional pre-defined validators are:
- max
- min
- not-null
- pattern(for regex validations)
and more.
You can also define a custom function if you need it tho
CodePudding user response:
If you want to change the color of the "*", add this .css to your "styles.css" (not in the component.css)
.mat-focused .mat-form-field-required-marker
{
color:blue
}
.ng-invalid.ng-touched.mat-focused .mat-form-field-required-marker
{
color:red
}
In only want to hide the "*" you use
[required]="form.hasError('required','name')?true:null"
See the stackblitz