0

I am trying to create a custom phone input component by implementing ControlValueAccessor and Validator in Angular, but I have an issue with mat-error not triggering. The FormGroup seems to work, as it detects value changes and correctly identifies if the phone number is invalid. The FormGroup errors include { "notValidNumber": true }, but somehow the phone input doesn't get the information back that its errorState should be true.

Is there a manual way to trigger the errorState for the input component mat-form-field, or can you suggest any other solution?

Here is the code for the parent component:

<form [formGroup]="formGroup">
...
        <div>
            <app-phone-input formControlName="phone" [phoneNumber]="this.entryAddEditService.entryObject.mobile!">
            </app-phone-input>
        </div>
...
</form>

        this.formGroup = this.formBuilder.group({
            ...
            phone: [this.entryAddEditService.entryObject.mobile],
            ...
              }); 

And here is the code for the input component:

<mat-form-field floatLabel="always">
    <mat-label>{{ "sk.entry.infoPhone" | translate }}:</mat-label>
    <input matInput id="info-phone"/>
    <mat-error>
    "}}
    </mat-error>
</mat-form-field>

@Component({
    selector: 'app-phone-input',
    templateUrl: './phone-input.component.html',
    styleUrls: ['./phone-input.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: PhoneInputComponent,
            multi: true
        },
        {
            provide: NG_VALIDATORS,
            useExisting: PhoneInputComponent,
            multi: true
        }
    ]
})

export class PhoneInputComponent implements ControlValueAccessor, Validator {
...


    validate(_: AbstractControl): ValidationErrors | null {
        if (this.phoneInput && !this.phoneInput.isValidNumber() && this.phoneInput.getNumber()) {
            return { "notValidNumber": true };
        }
        return null;
    }
...

I expect that it should show input surrounded with red border and show my error message.

2
  • What is this.phoneInput? Commented Apr 17, 2023 at 17:40
  • @JSONDerulo this.phoneInput refers to an instance of the intl-tel-input object. Commented Apr 18, 2023 at 12:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.