簡體   English   中英

Angular - 動態加載的模塊/組件中的更改檢測而不使用`ChangeDetectorRef`

[英]Angular - change detection in dynamically loaded module/component without using `ChangeDetectorRef`

我用編譯器的compileModuleAsync編譯了一個 Angular 模塊(動態加載模塊),並希望將模塊的一個組件插入到視圖中。

我試圖將組件插入到ViewContainer中,但該組件不會自動檢測到更改。 每次更新組件的屬性時,我都應該調用changeDetectorRef.detectChanges

有沒有辦法在不使用changeDetectorRef的情況下實現這一點?

Angular 版本為10.0.4

我加載組件的示例代碼:


我加載另一個組件的組件:

<ng-template #dynamic></ng-template>
@ViewChild('dynamic', { read: ViewContainerRef })
dynamic: ViewContainerRef;

constructor(
    private compiler: Compiler,
    private injector: Injector
) {}

async ngAfterViewInit() {
    // Load a module dynamically
    const exampleModule = await import('../example/example.module').then(m => m.ExampleModule);
    const moduleFactory = await this.compiler.compileModuleAsync(exampleModule);
    const moduleRef = moduleFactory.create(this.injector);
    const componentFactory = moduleRef.instance.resolveComponent();
    const ref = container.createComponent(componentFactory, null, moduleRef.injector);
}

示例模塊:

@NgModule({
    declarations: [
        ExampleComponent
    ],
    imports: [...]
})
export class ExampleModule {
    constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

    public resolveComponent(): ComponentFactory<ExampleComponent> {
        return this.componentFactoryResolver.resolveComponentFactory(ExampleComponent);
    }
}

調用detectChanges的示例:

示例組件

<button (click)="toggle()">Show/Hide</button>
<span *ngIf="show">Show</span>
public toggle() {
  this.show = !this.show;
  this.cdr.detectChanges(); // <- I want to not use this.
}

我使用此服務來創建組件集輸入:

@Directive({
  selector: '[formField]'
})
export class FormFieldDirective implements Field, OnChanges, OnInit, AfterViewInit {
  @Input() config: FieldConfig;
  @Input() lang: string;
  @Input() group: FormGroup;

  @Input('class') classList: string = 'col-12';

  component: ComponentRef<Field>;

  constructor(
    private resolver: ComponentFactoryResolver,
    private container: ViewContainerRef,
    private renderer: Renderer2
  ) { }

  ngOnChanges() {
    if (this.component) {
      this.component.instance.config = this.config;
      this.component.instance.group = this.group;
    }
  }

  ngOnInit() {
    if (!components[this.config.type]) {
      const supportedTypes = Object.keys(components).join(', ');
      throw new Error(
        `Trying to use an unsupported type (${this.config.type}).
        Supported types: ${supportedTypes}`
      );
    }
    const component = this.resolver.resolveComponentFactory<Field>(components[this.config.type]);
    this.component = this.container.createComponent(component);
    this.renderer.addClass(this.component.location.nativeElement, this.config.widthClass ? this.config.widthClass : 'col-12');
    this.component.instance.config = this.config;
    this.component.instance.group = this.group;
    this.component.instance.lang = this.lang;
    if (this.config.type === ModelType.group) {
      this.component.instance.innerForm = this.group.get(this.config.name) as FormGroup;
    }

  }

  ngAfterViewInit() {
    this.config.label += 'cica';
  }
}

用法:

<div [ngClass]="formClass" [formGroup]="form">
    <ng-container *ngFor="let field of config;" formField [config]="field" [lang]="lang" [group]="form"> </ng-container>
    <ng-content></ng-content>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM