3

I have a library of web components that will be used in different angular projects. I am using @angular/elements to turn my components to reusable elements then serve it using http-server.

one component I created was a custom h1:

h1-component.ts

import { Component, Input, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-h1',
  templateUrl: './h1.component.html',
  styleUrls: ['./h1.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom
})

export class H1Component {
  private _text: string = '';

  @Input() set text(text: string) { this._text = text; }
  get text(): string { return this._text; }
}

h1-component.html

<h1>{{ text }}</h1>

in my app.module.ts, I declared my custom element as

const h1El = createCustomElement(H1Component, {
  injector: this.injector
});
customElements.define('custom-h1', h1El);

My application is set up according to https://angular.io/guide/elements

After finishing all my components, I proceeded to test them by creating another angular application, setting my environment to load my script. However, this is when I noticed that my custom components are not taking my @Input values.

In my new application:

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  header = "Custom header";
}

app.component.html

<custom-h1 text="{{ header }}"></custom-h1>

After running ng serve on my new application and http-server on my library of components, I should expect to see "Custom header". However, I don't see any results.

If I put a string value inside text (ie. <custom-h1 text="Custom header string"></custom-h1>), I am able to see the correct output which is "Custom header string".

Any thoughts or suggestions? or reference? Thank you.

2 Answers2

0

I think this is the explanation here: https://github.com/angular/angular/issues/29050. If you console.log() your variables in the ngOnChanges() hook you will get the correct values but in ngOnInit() they are still undefined. The order in which the hooks execute changes when using custom elements. That's why in your it was undefined. In my case I am still looking to see how I can force ngOnChanges() to run first and then ngOnInit() but no luck yet.

so do:

ngOnChanges(): void {
    this._text = text;
}

see this: Angular Elements: @Input decorator not working with variables

whiteadi
  • 133
  • 2
  • 17
0

maybe this will help <custom-h1 [text]="header"></custom-h1>

Ogoniok
  • 21
  • 5