question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Angular Element issue with change detection running on Property value change

See original GitHub issue

🐞 bug report

Affected Package

The issue is caused by package @angular/elements

Is this a regression?

Unknown

Description

In an Angular Element hosted by a JQuery project, if JQuery tries to set the value of a property defined with the @Input() decorator, the Angular Element does not see the value change.

🔬 Minimal Reproduction

Steps for a minimal reproduction:

  1. ng new PropBindingTest (No Routing, Use CSS)
  2. cd PropBindingTest
  3. ng add @angular/elements
  4. ng add ngx-build-plus
  5. Change app.module.ts
import { Injector, NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { BrowserModule } from '@angular/platform-browser';
import { createCustomElement } from '@angular/elements';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  entryComponents: [
    AppComponent
  ]
})
export class AppModule {
  constructor(private injector: Injector) {
  }

  ngDoBootstrap() {
    const customEl = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('prop-binding-test', customEl);
  }
}
  1. Change app.component.ts
import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';

@Component({
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnChanges {
  @Input() public testProp: { header: string, paragraph: string };

  public ngOnInit(): void {
    console.log('ngOnInit Fired.', this.testProp);
  }

  public ngOnChanges(changes: SimpleChanges): void {
    console.log('ngOnChanges Fired.', changes, this.testProp);
  }
}
  1. Change app.component.html
<h1 *ngIf="testProp">{{testProp.header}}</h1>
<p *ngIf="testProp">{{testProp.paragraph}}</p>
  1. Remove import 'zone.js/dist/zone'; from polyfills.ts, final polyfills.ts should be empty
  2. Add import 'zone.js'; to top of main.ts, final main.ts should be
import 'zone.js';

import { AppModule } from './app/app.module';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));
  1. Change tsconfig.json target from ‘es5’ to ‘es2015’, final tsconfig.json should look like
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
  1. ng build --prod --single-bundle (the single-bundle option comes from ngx-build-plus)
  2. Copy & Paste PropBindingTest/dist/PropBindingTest/main.d80c1f431a277f0798b0.js into a jQuery project folder
  3. In JQuery application, add the following
    jQuery('head').append('<script src="../assets/main.d80c1f431a277f0798b0.js"></script>');
    const propTest = document.createElement("prop-binding-test");
    jQuery('#some_location').after(propTest);
    propTest.testProp = { header: "I Hope This Works", paragraph: "This is very exciting." };
  1. Run your jQuery app, and open your console. You should see ngOnInit Fired. undefined as the only printed line, and your custom component should exist in the DOM but display nothing, as propTest was never set. If you take a look at the code in app.component.ts, this means that ngOnChanges is never actually running, otherwise we should see another log statement ngOnChanges Fired., which we don’t. You can also add console.dir(propTest); and see that testProp IS being set on the HTMLElement, it just doesn’t propagate to the Angular.

If I am missing something, can someone please point me towards the proper documentation? I found it very difficult to find good information on the process of creating an Angular Element and hosting it in a non-angular application.

dependencies from final package.json are:

  "dependencies": {
    "@angular/animations": "~7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/elements": "^7.2.15",
    "@angular/forms": "~7.2.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "document-register-element": "^1.7.2",
    "ngx-build-plus": "^7.8.3",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  }

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
antchcommented, Jun 14, 2019

Just FYI, when you are using the Angular CLI the JS bundles are loaded at the end of the body, so I would suggest following that same approach even if you’re just using Custom Elements.

If you run ng serve on an Angular CLI project and inspect the generated HTML, you will see things structured this way:

<body>
    <my-app></my-app>
    <script type="text/javascript"><!-- index.html inline JavaScript would go here --></script>
    <script type="text/javascript" src="/path/to/runtime.js" />
    <script type="text/javascript" src="/path/to/polyfills.js" />
    <script type="text/javascript" src="/path/to/vendor.js" />
    <script type="text/javascript" src="/path/to/main.js" />
</body>
0reactions
angular-automatic-lock-bot[bot]commented, Sep 15, 2019

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Angular Change Detection - How Does It Really Work?
By default, Angular Change Detection works by checking if the value of template expressions have changed. This is done for all components. We ......
Read more >
change in property value not triggering change detection in ...
I am currently trying to implement disabling the Add button based on setting the property in the component in my angular 4 application....
Read more >
The Last Guide For Angular Change Detection You'll Ever Need
Change Detection does not perform a deep object comparison, it only compares the previous and current value of properties used by the template...
Read more >
Simplifying Angular Change Detection - Telerik
The onPush change detection strategy instructs Angular to run change detector on the component and its subtree only when a new reference is ......
Read more >
Angular change detection and runtime optimization
Change detection is a highly optimized performant, but it can still cause slowdowns if the application runs it too frequently. In this guide,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found