Jonathan
Jonathan

Reputation: 4918

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: https://medium.com/@matanlurey/lazy-loading-with-angular-dart-14f58004f988. 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;

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

  go() {
    otherEdit.loadLibrary();
    canOther = true;
  }
}

Upvotes: 1

Views: 555

Answers (2)

Jonathan
Jonathan

Reputation: 4918

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
    holder.clear();

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

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

  mainComponent(this. _componentLoader){}
}

Upvotes: 0

rkj
rkj

Reputation: 9311

I do not think you can do it directly. What you can do instead is using DynamicComponent from Angular2_components and pass the type after lazily loading it.

Upvotes: 2

Related Questions