Reputation: 121
Input data : angular 6, angular material 2.
My custom validation "password-matcher" set invalid for "passGroup". Example:
<div ngModelGroup="passGroup" password-matcher #passGroup="ngModelGroup">
<div class="formGroup">
<mat-form-field>
<input
matInput
type="password"
class='inputs'
[(ngModel)]='reg.password'
name='password'
required
minlength="8"
(input)='onChangeReg(reg)'
>
</mat-form-field>
</div>
<div class="formGroup">
<mat-form-field class="example-full-width">
<input
matInput
type="password"
class='inputs'
[(ngModel)]='reg.repeatPassword'
name='repeatPassword'
required
minlength="8"
(input)='onChangeReg(reg)'
>
</mat-form-field>
</div>
</div>
How can I set invalid to mat-form-field
, if ngModelGrou
p is invalid
?
for example: <mat-form-field setValidation='passGroup.invalid'>
Upvotes: 1
Views: 9989
Reputation: 17908
Theoretically, you would need to provide a custom ErrorStateMatcher
for the MatInput
control. Angular Material has an example here. In the ErrorStateMatcher
's isErrorState
function you will need to access the control's parent group and use it's state to return the state for the field control.
However, I'm not sure this will work as expected. Because the parent group state is dependent on the child control state, you are creating a circular dependency. So instead, you might need to check the other child controls for errors rather than explicitly checking the parent state.
From a design perspective, in general you probably shouldn't do this, because the point of showing errors is to bring the user's attention to which fields need correction. Marking a field that has no error as in error when it is another field that has the error will confuse users. In the case of a login control with only username and password fields, I can see that this might be beneficial in order to discourage hacking.
Upvotes: 2