Home > Blockchain >  How to validate input in child component
How to validate input in child component

Time:01-24

I am migrating an AngularJS 1.6 application to Angular 12. I am having a problem migrating a form to a Angular template-driven-form:

<form novalidate #myAwesomeForm="ngForm" name="myAwesomeForm">
    [...]
</form>

which contains input fields inside of child-components:

<my-child-component
    [model]="myModel"
    [fieldId]="'someText'">
</my-child-component>

In the AngularJS-form we could easily validate all those nested input fields via e.g.

formName.inputName.invalid

But this doesnt seem to be working anymore. I was able to add the inputs to the NgForm via

@Component({
    selector: 'my-child-component',
    templateUrl: './my-child-component.component.html',
    viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})

in the child component, but this only gives me the possibility to check if the whole form is valid. I can also get all the input values of the form via

myForm.value

which returns an object with all field-names and their values, but I can't check a specific input field to show a more specific error message or styling this input, like

<div [ngClass]="myAwesomeForm.childComponentInputField.invalid ? 'has-error' : ''">
    <my-child-component
        [model]="myModel"
        [fieldId]="'someText'">
    </my-child-component>
</div>

Is there some way I can achieve that in Angular?

CodePudding user response:

You should use reactive-forms here. Build your form via the form-builder's (injected via the constructor) group-method. There you can also set Validators to your form-controls (inputs).

See: https://angular.io/guide/reactive-forms https://angular.io/guide/reactive-forms#validating-form-input

CodePudding user response:

In a template-driven Angular form you can always get a reference to any control-enabled component and then just check its validity the same way you would do with a form or with a component in AngularJS:

<form #myAwesomeForm="ngForm">
    <my-child-component-1 [model]="myModel1" #control1></my-child-component-1>
    <my-child-component-2 [model]="myModel2"></my-child-component-2>

    <div>Form is <span *ngIf="myAwesomeForm.invalid">not</span> valid</div>
    <div>Control 1 is <span *ngIf="control1.invalid">not</span> valid</div>
</form>
  •  Tags:  
  • Related