懒加载组件的Angular 2+访问/更改变量

问题描述 投票:0回答:1

我希望在延迟加载后将使用NewDataSet

我尝试添加@Input() DataListprivate DataList,但不起作用。

app.component.html:

<ul>
<li *ngFor="let Data of DataList">{{Data.Name}}></li>
</ul>

<button (click)='getLazy()'>Lazy Load New DataSet</button>

app.component.ts:

import OldDataSet from '../assets/OldDataSet.json';

...

export class AppComponent {

DataList:Array<Object> = OldDataSet;

  constructor(
    private viewContainerRef: ViewContainerRef,
    private cfr: ComponentFactoryResolver
  ) {}

  async getLazy() {
    this.viewContainerRef.clear();
    const { Lazy1Component } = await import('./lazy1.component');

    this.viewContainerRef.createComponent(
      this.cfr.resolveComponentFactory(Lazy1Component)
    );
  }
}

lazy1.component.ts:

import NewDataSet from '../assets/NewDataSet.json';

...

export class Lazy1Component implements OnInit {

  ngOnInit(): void {
    this.DataList = NewDataSet
  }
}
javascript angular typescript lazy-loading
1个回答
0
投票

https://stackblitz.com/edit/angular-dynamic-component-problem

请看一个实时版本。我希望该解决方案能够满足您的需求。

import {
  Component,
  ViewChild,
  ComponentFactoryResolver,
  ViewContainerRef,
  Type
} from "@angular/core";
import { PlaceholderDirective } from "./placeholder.directive";

import { DatasetAComponent } from "./dataset-a.component";
import { DatasetBComponent } from "./dataset-b.component";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html"
})
export class AppComponent {
  hostViewContainerRef: ViewContainerRef;

  @ViewChild(PlaceholderDirective, { static: false })
  datasetHost: PlaceholderDirective;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

  onLoadA() {
    this.loadNewDataset(DatasetAComponent, "dataset A loaded.");
  }

  onLoadB() {
    this.loadNewDataset(DatasetBComponent, "dataset B loaded.");
  }

  onClear() {
    this.hostViewContainerRef.clear();
  }

  loadNewDataset(
    datasetComponent: Type<DatasetAComponent> | Type<DatasetBComponent>,
    message: string
  ) {
    const datasetCmpFactory = this.componentFactoryResolver.resolveComponentFactory(
      datasetComponent
    );

    this.hostViewContainerRef = this.datasetHost.viewContainerRef;

    this.hostViewContainerRef.clear();

    const componentRef = this.hostViewContainerRef.createComponent(
      datasetCmpFactory
    );
    componentRef.instance.message = message;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.