is there a way lazy load a component in angular 2 dart?


I have a component that uses another component with a ngIf statement. I would like to only load the second component once the ngIf evaluates to true.

EDIT: found an article that can almost do what I need: However, after the library loaded, it takes the whole view of the component. In my case, I need to insert it into a specific place in the html of the parent component.

Something like:

import '../other/edit_component.dart' deferred as otherEdit;

    selector: 'edit-component',
    template: '<other-component *ngIf="canOther"></other-component>
    <button type="button" (click)="go()"></button>',
    directives: const [
class EditComponent {
  bool canOther = false;

  go() {
    canOther = true;


Just made it work. Used the DynamicComponent as example from rkj answer.

// the lib that has the component to be loaded
import 'package:somecomponent.dart' deferred as mycomponent;

class mainComponent {
  // <div #holder></div> element that we will append the component
  @ViewChild('holder', read: ViewContainerRef)
  ViewContainerRef holder;

  // this will load the component dynamically
  final DynamicComponentLoader _componentLoader;

  load() {
    // clear the html

    // load the component dynamically
    ComponentRef componentRef = await _componentLoader
      .loadNextToLocation(componentType, holder);

    // set some attributes like you would with [attributes]="somevar"
      ..attribute = somevar;

  mainComponent(this. _componentLoader){}

Answered By – Jonathan

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *