Interesting problem, so please read till the end. what I want to achieve is separating template in another js file and lazyload it when required. This same thing when done in React ecosystem works, but stencil doesn't! Triage Repo https://github.com/pranav-js/triage-repo
I am having my tsx template in another .js file say
template-three.js has simple onClick which only alerts
import { h } from '@stencil/core';
export const template_three = () => {
return <button onClick={() => alert()}>Template three here</button>;
};
when I try to call this method by importing in component-two.tsx like this
import { Component, Fragment, h, Host, State } from '@stencil/core';
@Component({
tag: 'component-two',
styleUrl: 'component-two.css',
shadow: true,
})
export class ComponentTwo {
@State() showComponentOne: any;
method: any;
template: string = '';
constructor() {}
componentWillRender() {
this.fetchComp(2);
}
// lazy load template when needed based on type passed
fetchComp(type) {
let this_ = this;
switch (type) {
case 0:
import('./template').then(module => {
this.showComponentOne = module.template_one;
});
break;
case 1:
import('./template-two').then(module => {
this.showComponentOne = module.template_two;
});
break;
case 2:
import('./template-three').then(module => {
this.showComponentOne = module.template_three;
);
break;
default:
break;
}
}
clicked() {
alert();
}
methodHere() {}
// check if template received then simply call that method with this attached
render() {
let this_ = this;
return this.showComponentOne ? this.showComponentOne.apply(this) : <div></div>;
}
}
View renders, but event listners are not working :/, not even a simple alert :(. When I inspect, I don’t see any event attached to button. however if same function I keep inside component class, it works :( !!!
check two different objects when template defined inside and outside component.
Can you tell me what I am doing wrong here.
I can’t keep templates in component only cause I have many UI’s for same logic. So far, I didn't get any way on internet this answer doesn't help either Passing custom template to stencil component