current position:Home>Dynamic components of angular

Dynamic components of angular

2022-04-29 09:18:30from_ the_ star

This is the website Dynamic components Explanation , I don't know how you feel , Anyway, I was a beginner , I didn't understand much , One first two big , No wonder Angular Not as good as Vue fire , It's really easy to dissuade .

Use scenarios

Let's first clarify the usage scenario of dynamic components , Dynamically load components when the code is running , For ordinary people , The code needs to be based on the specific situation ( For example, the user's operation , Request results from the background ) Make sure to load some components in some places , These components are not static ( Not fixed ).

An example of the official website is , Build a dynamic banner , Advertising components will continue to launch new , It is obviously unrealistic to reuse a template that only supports static component structure .

Another common example , Dynamic pop up , The components that pop up are uncertain 、 Constantly updated , A purchase box pops up here and there , Then you need to pop up the style selection box , Static component structure template can not meet the growing needs of the masses .

How to achieve

Then let's find a handle , See what it takes to implement dynamic components .

One 、 Where to put dynamic components

We need to know where to add dynamic components , That's the anchor point . So what can be used to load components ?

You may want to say , Isn't the component loaded on the anchor , The anchor point is not DOM Node ? That's loading, of course DOM In the node .

Let's review Angular operation DOM Common ways to do it , Native JS operation DOM Don't think about it , You think it can return to what you can load Angular The object of the component ?

Angular It provides a method called DOM Query Technology , Mainly from @ViewChild and @ViewChildren Decorator (decorators), Both functions are basically the same .

@ViewChild: Returns a single reference , In the view DOM Find the first element or instruction that can match the selector .

@ViewChildren : Return from QueryList Object wrapped multiple references , In the view DOM Find all elements or instructions that match the selector in .

Basic grammar :

@ViewChild([reference from template], {read: [reference type]});

DOM Query The objects found by the technology are divided into three categories :

  1. ElementRef: If it mounts something similar span Simple html Elements ;
  2. TemplateRef: If it mounts template Elements ;
  3. ViewContainerRef: It is impossible to infer , Generally, programmers should be in read Named in the , whatever DOM Elements can be used as view containers .

We inquire through the official website API You can see that only ViewContainerRef Is the container that can attach one or more views to components , That is, only it can load components . But here's the thing , It is a new component that can be used as its brother ( node ) Of DOM Elements ( Containers ), It's brother , Not father and son .

well , We decided to use ViewContainerRef To load the container , obtain ViewContainerRef There are two ways :

The first is the passage above DOM Query Inquire about @ViewChild obtain

<ng-container #addComp></ng-container>


@ViewChild('addComp', {read: ViewContainerRef}) adComp:ViewContainerRef;

The second is the example on the official website , With dependency injection

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ad-host]',
})
export class AdDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

Anchor setting ng-template On , Get... Through instruction injection ViewContainerRef

template: `
            <div class="ad-banner-example">
              <h3>Advertisements</h3>
              <ng-template ad-host></ng-template>
            </div>
          `

Two 、 How to get an instance of a component

Load components into the view , Not a simple one new Is instantiated , Again append、insert Something that can be attached . Dynamic components need to be compiled and stored by the compiler in advance , And then to ComponentFactory encapsulated , After that Component The instance should pass ComponentFactory To create . You can look at this article [ translate ] About Angular Dynamic components what you need to know , But it refers to the use of SystemJsNgModuleLoader The module loader has been eliminated .

ComponentFactoryResolver A simple registry , mapping Components To ComponentFactory Generated classes that can be used to create component instances . It can be used to get the factory of a given component type , Then use the factory's create() Method to create a component of this type .

Let's take a look at the official website example code , The following is not the complete code


 // Inject ComponentFactoryResolver
 constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

 loadComponent() {
     ......
    //  Get the generated... That can be used to create an instance of the advertising component ComponentFactory
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    // Get the container that loads the component 
    const viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();

    //  Put the components in the container , Pass some more parameters to it 
    const componentRef = viewContainerRef.createComponent(componentFactory);
    (<AdComponent>componentRef.instance).data = adItem.data;
  }

You think it's over , Do you think the code written in this way can run ? wet behind the ears , Let Qianlang tell you some points to pay attention to :

  1. Angular Components in 、 Instructions 、 They are all encapsulated in pipes , Take components as an example , If you want to use other module components , Other modules must have export This component , And you should also import Other modules . So remember to import and export the instructions of the official website example .
  2. If it's a dynamic component , The component must be registered in the module entryComponents attribute , But you don't have to export,import Modules are still needed .

There's another one on the official website Pop up service Example , You can combine them to see , Deepen the understanding .

copyright notice
author[from_ the_ star],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290630081637.html

Random recommended