Ivan Bacher
Ivan Bacher

Reputation: 6154

Dynamically add custom component to loaded DOM (aurelia.js)

Is it possible to add a custom component to the DOM once it has already been loaded?

E.g. When clicking a button

Template

<template>
    <button click.delegate="add_component()"> Press me </button>
</template>

Viewmodel

@inject(Element)

export class App {

  constructor(element) {
      this.element = element;
  }

  function add_component() {
     var component = document.createElement('<customElement></customElement>');
     this.element.appendChild(component);
  }
}

Upvotes: 3

Views: 1640

Answers (1)

Rytmis
Rytmis

Reputation: 32047

There's more than one way to do that, actually. Depending on your actual need, you might get away with using the compose element if your need is to dynamically switch views.

Another approach is to use Aurelia's View Compiler to compile the markup into a view, then create a View Slot (there's some discussion on the topic in this aurelia-templating GitHub issue). With View Slots, it should be possible to dynamically add multiple views one after another.

However, if your actual need is anything close to your example, you can simply get away with something like this:

<template>
    <button click.delegate="add_component()"> Press me </button>
    <custom-element if.bind="hasCustomElement"></custom-element>
</template>

in the view and this:

export class App {
  @observable hasCustomElement = false;

  function add_component() {
      this.hasCustomElement = true;
  }
}

in the view model. The custom element will only be appended to the dom when the if.bind condition becomes true and removed if it becomes false.

Upvotes: 2

Related Questions