1

I am converting my advance search component used inside my landing page into Lazy Loading.

My landing page html:

<button (click)="onAdvanceSearch()"></button>
<ng-template  #formComponent></ng-template>

My landing page .ts file

  @ViewChild('formComponent', { read: ViewContainerRef })
  formComponent!: ViewContainerRef;

  async loadAdvanceSearchForm() {
    const { MaterialAdvanceSearchComponent } = await import(
      '../../material-advancesearch/material-advancesearch.component'
    );
    this.formComponent.clear();
    this.formComponent.createComponent(MaterialAdvanceSearchComponent);
  }

  onAdvanceSearch(): void {
    this.loadAdvanceSearchForm();
  }
  1. Everything works fine, but I am not sure how to pass the data as Input() & how to capture Output() event.

  2. Previously it was simple as below

    <app-material-advancesearch [searchkeywords]="searchkeywords" (notifyMaterialList)="refreshLists($event)"></app-material-advancesearch>
    
  3. Now after converting into Lazy Load component - where shall I mention my Input() & Output() properties ?

Thanks in advance

user2869612
  • 607
  • 2
  • 10
  • 32
  • 3
    See https://netbasal.com/a-new-way-to-set-inputs-on-angular-componentrefs-6214f95db63d. – derstauner Mar 22 '23 at 13:39
  • 1
    Technically you're lazy loading the component, but you're going to get more help if you call this "dynamically creating" a component since you're creating and injecting it via code. "Lazy loading" a component in Angular (especially v14+ where standalone components are a thing) refers to using `loadComponent` in the router to only fetch the component's bundle once a particular route is activated. – D M Mar 22 '23 at 14:24
  • Thank you @derstauner - worked for Inputs. https://stackoverflow.com/questions/54193386/output-from-dynamically-created-component-in-angular-6 => This gave answer related to Output. Please post as an answer so that I can accept it – user2869612 Mar 22 '23 at 14:35

1 Answers1

1

In order to set the input properties of a dynamically added / lazy loaded component, you have to store the reference to it in a variable and then access it's instance property like this:

const ref = this.formComponent.createComponent(MaterialAdvanceSearchComponent);
ref.instance.someInputProperty = 'someValue';

However, this approach has some drawbacks (see this post).

In Angular v14 a new method was introduced to overcome this issues. You can now set the input properties like this:

ref.setInput('someInputProperty', 'someValue');
derstauner
  • 1,478
  • 2
  • 23
  • 44