1

I have a custom component for my form: app-form

@Component({
  selector: "app-form",
  template: `
  <form (ngSubmit)="onSubmit()">
      <div class="row">
        <ng-content></ng-content>
      </div>
      <button type="submit">Save</button>
  </form>
  `,
  animations,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: FormComponent,
      multi: true
    }
  ]
})

and i have a custom component for my inputs: app-form-text

@Component({
  selector: "app-form-text",
  template: `
  <div class="form-group"
      [class.has-success]="nameval.valid && (nameval.dirty || nameval.touched)"
      [class.has-danger]="nameval.invalid && (nameval.dirty || nameval.touched)">
      
      <input type="text" class="form-control"
        [class.form-control-success]="nameval.valid"
        [class.form-control-danger]="nameval.invalid && nameval.dirty"
        #nameval="ngModel" [name]="nameval"  maxlength="250" minlength="2" [(ngModel)]="value"
        required [appNmsValidators]='ValidationType'>
        <div *ngIf="nameval.errors && (nameval.dirty || nameval.touched)">
          <p *ngIf="nameval.errors.required">{{ReqErMsg}}</p>
          <p *ngIf="nameval.errors.minlength">{{MinErMsg}}</p>
          <p *ngIf="nameval.errors.appNmsValidators">{{Cu1ErMsg}}</p>
        </div>
      <small class="form-text text-muted"></small>
  </div>
  `,
  animations,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: FormTextComponent,
      multi: true
    }
  ]
})

i use them as follow:

<app-form [FormName]="'BaseCodeForm'">
    <div class="col-md-6">
      <app-form-text required name="typeCode"   
        [(ngModel)]="BaseCodeModel.typeCode">
      </app-form-text>
    </div>
    <div class="col-md-6">
      <app-form-text required name="descCode" 
        [(ngModel)]="BaseCodeModel.descCode">
      </app-form-text>
    </div>
  </app-form>

how can i access form validation in app-form component?

1 Answer 1

1

In app-form component, you shoud try to inject the NgForm instance using @ViewChild

@ViewChild(NgForm) form: NgForm;

It should be accessible in the ngOnInit() method

Sign up to request clarification or add additional context in comments.

1 Comment

This code does not work. Please see this sample: stackblitz.com/edit/angular-customcomponent

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.