How to do Angular2/4 validation with 3rd party JS components

angular 2 form validation example
how to check email already exist in database in angular 6
changing the behavior of a 3rd party angular component
angular 2 form validation tooltip
angular 2 validation on button click
angular 2 phone number validation
include external js file in angular 4 component
angular 4 form validation example

When it comes to Angular 2 validation, I saw different approaches. The basic is to use either HTML5 and template/model binding or forms with assigned validators.

However when it comes to special rules it needs a lot of coding and with template binding (so no forms) mostly results in validation being scattered through HTML and TS code.

Also another annoying thing around validation is that you need to alter validation rules in TS and also add extra HTML code to have those values on the page rendered (although this can be automated via directive)...

Anyhow the ideal solution would be to use rules to model properties which then generates error messages to the controls. Similarly to .NET fluent validation and ModelState or in JS world similar to validation:

  1. Is something similar possible in Angular2+?
  2. How/where to wire check (based on model change) to a 3rd party (JS) library? Like fluent-ts-validator or flient-validator.
  3. How to set errors on controls, especially when we have f.e. controls inside controls...

First thing we will need is to link the FormControls to the input elements. It's not provided out of the box. The only solution so far (at least for pure ngModel binding) is the one i have posted here.

The code below does not work with pure ngModel binding, so I did a lot of experiments. Latest, also confirmed by Maximillian Schwarzmuller should be the one:

    selector: '[ngModel]', // or 'input, select, textarea' - but then your controls won't be handled and also checking for undefined would be necessary
export class NativeElementInjectorDirective {
    constructor(private el: ElementRef, private control : NgControl) {
        (<any>control.control).nativeElement = el.nativeElement;

So if this directive is provided and exported in the main module, it will attach a custom nativeElement property to all FormControl.

Angular 2 Series - Part 5: Forms and Custom Validation, When it comes to Angular 2 validation, I saw different approaches. The basic is to use either HTML5 and template/model binding or forms with assigned  Angular 4 uses novalidate attribute by default in its form element at run time and hence while submitting form, HTML 5 validation will not work. If we are using Angular 2, we need to write novalidate attribute in our form element to use Angular form validation. In Angular 4 template-driven form we can use ngNoForm to enable HTML 5 validation

Next thing was to know how to build nested forms properly - see link here!

And also not just forward ngForm but also ngModelGroup:

    selector: 'TestAddress',
    templateUrl: './address.location.html',
    viewProviders: [
        { provide: ControlContainer, useExisting: NgForm },
        { provide: ControlContainer, useExisting: forwardRef(() => NgModelGroup) },
    providers: [ MakeProvider(TestAddress) ]
export class TestProspectAddressLocation extends AbstractValueAccessor<any> {

We had to use AbstractValueAccessor and thus a MakeProvider too. Here's the link!

Last piece: a way to access those FormControls:


Now you can subscribe to formValueChange and user 3rd party for validation, access any control by a path expression, use control.setErrors([]) or just append a HTML via jQuery aft. input.

External JavaScript dependencies in Typescript and Angular 2 , Angular 2 Series - Part 5: Forms and Custom Validation In this tutorial, we'll take a look at how to use the classes and directives related to forms in Angular 2 by Once that's done, let's create a component for our first form. Note that async validators are passed in as the third argument to the Control . With followed this post angular-4-universal-app-with-angular-cli and this cli-universal-demo project, I encountered a problem as below. When node starts dist/server.js it shows an error: (function (exports, require, module, __filename, __dirname) { export * from ‘./scn-filter-builder’ scn-filter-builder is my module.

Still looking for:

  1. To create some directive that could add a [(ngModel)] binding to every control which has ngModel attribute and a name defined - whereas the expression assigned should be 'value.' + name attribute value
  2. A way to replace a div added by jQuery dynamically with an angular component - and since the div is dynamic, @ViewChild(selector) can't be used
  3. Using nested forms with [(ngModel)] binding does produce a weird FormGroup structure, so either the custom angular component should auto-define ngModelGroup='name attr. value' or using ngControlOptions standalone or another way should be foud which does not do a mess...

Changing the behavior of a 3rd party Angular Component, Angular 2.0 and Typescript make it very easy to import external Any components you install with npm are available to be imported. Probably the hardest part in working with Angular 2 for me has been figuring out where modules live. Synchronous and Asynchronous Validators for Template Validation  As developers, we aim to use existing libraries in order to avoid reinventing the wheel. Unfortunately, Angular is still relatively young, and we cannot find an Angular component for everything we need. The purpose of this article is to demonstrate use cases in which Angular components can be connected with vanilla JS libraries. #Example One

So #2 from the list above was possible to do.

We do use a ngModel selector to get a ref. to all inputs, of course we do have a main control (which contains validation related messages/code) and thus we ignore controls not inside that container.

Now here comes the trick: we do get a viewContainerRef to the input itself. This allows us to inject a control immediately after the input. Since injection is to that given viewContainer, when input get's hidden, the injected control is destroyed...

The code:

import {Directive, OnInit, Optional, ViewContainerRef} from "@angular/core";
import {NgControl} from "@angular/forms";
import {ValidationContainerDirective} from "./validation-container-directive";

This directive should match all inputs (ngModel)...
If it's inside a validation container, it'll process it...
    selector: '[ngModel]'
export class ValidationControlForInjectorDirective implements OnInit {

    private initialized: boolean = false;

    constructor(@Optional() private validationContainer: ValidationContainerDirective,
                private control: NgControl,
                private viewContainerRef: ViewContainerRef,
              ) {

        // skip if not inside a validation container...
        if (!this.validationContainer)

        // mark as initialized
        this.initialized = true;

    ngOnInit(): void {

        // skip if not initialized
        if (!this.initialized)

        var thisLocator = this.control.path.join(".");

        // check inputs...
        if (!thisLocator)
            throw new Error('Validation wire issues!');

        // add a control aft. the input...but disable it temporarily...
        this.validationContainer.injectComponent(this.viewContainerRef, thisLocator);


The injectComponent method above does just set up my control and attaches it to the viewContainerRef:

injectComponent(componentVcRef: ViewContainerRef, locator: string) {

    // create component
    var componentRef = componentVcRef.createComponent(this.componentFactoryForValidationControlFor);

    // basic set up (switching server/client messages on/off is done by the doCheckManagedComponents() fnc.
    (<ValidationControlFor>componentRef.instance).locator = locator;
    (<ValidationControlFor>componentRef.instance).isDynamic = true;
    (<ValidationControlFor>componentRef.instance).serverMessages = false;
    (<ValidationControlFor>componentRef.instance).clientMessages = false;
    (<ValidationControlFor>componentRef.instance).clientMessagesAlwaysVisible = this.clientMessagesAlwaysVisible;


    // NOTE:
    // registering of managed component is done via the component's ngOnInit function...
    // was moved there, because we need to keep track also of manually added validation-message-controls!

Using published libraries, Changing the behavior of a 3rd party Angular Component my need for tweaking the out-of-the-box behavior of the library components has also been growing. Once you have access to the instance, you can use plain old JavaScript tricks Angular forms (Reactive Form) including Angular Material and Custom Validator. In today's tutorial, we are going to utilize some of these new features to build an entire Angular application. Components, @NgModule, route guards, services, and more are just some of the topics we'll touch on. Finally, we'll implement token-based authentication with Auth0. The Angular Ecosystem. AngularJS 1.x was highly regarded as a robust

Glossary, See the Angular Update Guide for help. Adding a library to the runtime global scopelink. Legacy JavaScript libraries that are not imported into an app can be  b27lu changed the title How to load a 3rd party js file in webpack How to load a 3rd party js file May 7, 2016 ebeal added the question label May 13, 2016 This comment has been minimized.

Angular 2: Creating a powerful form validation component., For example, a custom builder can replace the third-party tools used by the During the bootstrap process, Angular creates and inserts these components into the index.html host web page. A JavaScript module that is intended to be imported by a user of an npm package. Template-driven forms use validator directives. jQWidgets Angular UI components will help you to build perfect looking web applications. Use the most advanced UI framework for Angular 9 and save your time for the business logic. Choose from more than 60 UI components for Angular .

Angular 2, NgModel and Custom Form Components, For those who have not used ng-messages, this is an AngularJS 1.x directive that So why don't we build a component that we can wrap any input in, like this: Preparing for the journey: part 1 The third path: The grail of Angu-LAHR. Angular 4 ElasticSearch example – Add Document to Index; Angular 4 ElasticSearch example – Get All Documents in Index; Angular 4 ElasticSearch example – Documents Pagination with Scroll; Angular 4 ElasticSearch example – simple Full Text Search; Angular 6 ElasticSearch – Quick Start – How to add Elasticsearch.js

Angular 7 sidebar example, You can have custom components and complex validation, too. First, let's create a form context which will be responsible for aggregating This part will be mostly taken care of by the Angular forms library They may be set by us or by third party providers whose services we have added to our pages. The webcomponents.js polyfill comes with a loader script that can be used to load only the polyfills a particular browser needs. It loads the polyfills dynamically, so it cannot be imported directly as a JS dependency that gets built by Webpack.

  • All my concerns on that validation is in detail described here:…
  • Hi, seems to be very impressive solution. May I ask how you display the results on the angular component?
  • @baHi Thanks. The results are shown using ng-bootstrap tooltips in the angular component. But you can display them any how you like.
  • i had a lot of work to do that display via an auto injected component, that is able to use angular templates and so on. the validation itself was an easy stuff to do, but the original fluent validator had to be patched to auto-add param names. that one works without extra validation classes, so IMO flexible in cases.
  • @baHI ok, mine uses tooltips with a <ul> to display the results. Easy enough to do. Also, mine is a Service oriented approach to form validation. Many advantages to that.