Passing Data to Angular Elements
Showcase how to pass dynamic data into Angular Elements using property bindings or attributes.
// Define an Angular component as a custom element
@Component({
selector: 'app-hello-world',
template: `<p>Hello, {{ name }}!</p>`,
})
export class HelloWorldComponent {
@Input() name: string;
}
// Bootstrap the component as an Angular Element
@NgModule({
declarations: [HelloWorldComponent],
entryComponents: [HelloWorldComponent],
})
export class HelloWorldModule implements DoBootstrap {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(HelloWorldComponent, { injector: this.injector });
customElements.define('app-hello-world', el);
}
}
This code snippet defines an Angular component 'HelloWorldComponent' with an input property 'name'. We then create a module 'HelloWorldModule' where the component is declared and bootstrapped as a custom element using 'createCustomElement'.
// Using the custom element dynamically in a non-Angular context
const helloWorldElement = document.createElement('app-hello-world');
// Set property directly
helloWorldElement.name = 'John Doe';
document.body.appendChild(helloWorldElement);
Here we create an instance of the custom element and set its 'name' property directly in JavaScript, then append it to the document body. This showcases how to pass dynamic data via property bindings.
// Alternatively, using the custom element with attribute binding
const helloWorldElementWithAttribute = document.createElement('app-hello-world');
helloWorldElementWithAttribute.setAttribute('name', 'Jane Smith');
document.body.appendChild(helloWorldElementWithAttribute);
In this snippet, we create another custom element and use 'setAttribute' to bind data to its 'name' property via attributes, then append it to the document body.