Search code examples
javascriptangulartypescriptangular-reactive-formsangular-forms

Angular reactive form value don't filled by third-party service


I have a reactive address form and third-party service for address lookups (Loqate in my case, and this service injected by injecting script in HTML).

Few of fields can be autocompleted/autofilled by the service (like in the GIF below). And few of fields are required. When user choose one of suggested address - form filled in UI (HTML), but not in Angular form in the component.

How I can detect changes by third-party service and fill form value?

For example form:

this.addressForm = this.formBuilder.group({
  Country: ['', Validators.required],
  OrderShippingAddressLine1: ['', Validators.required],
  OrderShippingAddressLine2: [''],
  OrderShippingAddressPostcode: ['', Validators.required]
});

A minimal example of components, but unfortunately without the service on Stackblitz.

enter image description here


Solution

  • If you use Loqate (as I do), you need to know about pca object in you window object.

    Loqate support sent me that piece of code for triggering change event

    pca.on("data", function(source, key, address, variations) {
      if (source === "address") {
        for (var i = 0; i < pca.platform.productList[key].PLATFORM_CAPTUREPLUS.bindings[0].fields.length; i++) {
          var pcaField = document.getElementById(pca.platform.productList[key].PLATFORM_CAPTUREPLUS.bindings[0].fields[i].element);
          if (pcaField) {
            pca.fire(pcaField, "change");
          };
        };
      };
    });

    Few more strings of code for change/patch form controls value and updateValueAndValidity, and that works