GenweiWu / Blog

个人技术能力提升
MIT License
4 stars 0 forks source link

angular2 动态组件 #51

Closed GenweiWu closed 5 years ago

GenweiWu commented 6 years ago

官方文档

https://angular.cn/guide/dynamic-component-loader

GenweiWu commented 6 years ago

如何处理Input()

直接在对应页面调用 子组件.data={...}

问题:无法触发ngOnchange方法

//下面的方法没有触发ngOnChanges方法,导致内容还是旧
instance.userId=1
instance.userId=2

规避方法

instance.changeUserId(1);
instance.changeUserId(2);

不要这样写

//这样会导致下面的判断(aaa)总是相同的
instance.userId=2;
instance.changeUserId(2);
GenweiWu commented 5 years ago

如何处理@Output()

或者

 private _afterAllClosedAtThisLevel = new Subject<void>();
GenweiWu commented 5 years ago

挂载到body

https://stackoverflow.com/a/41195304

constructor(
      private _viewRef: ViewContainerRef,
      private _hostDomElement: Element,
      private _componentFactoryResolver: ComponentFactoryResolver,
      private _appRef: ApplicationRef,
      private _defaultInjector: Injector) {
  }

Then : Creating the component in the current viewContainerRef , which in your case is your modal.

ngOnInit() {

        // Calls the factory to crate a brand new instance
        let componentFactory = this._componentFactoryResolver.resolveComponentFactory(ModalComponent);
        let componentRef = this._viewRef.createComponent(componentFactory);

    }

Then attaching it to the appRef

 (this._appRef as any).attachView(componentRef.hostView);

        this.setDisposeFn(() => {
          (this._appRef as any).detachView(componentRef.hostView);
          componentRef.destroy();
        });
GenweiWu commented 5 years ago

挂载到body

当前做法

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TestComponent);
    let componentRef = this.viewContainerRef.createComponent(componentFactory);
    componentRef.instance.userId = "123";

    document.body.appendChild(componentRef.location.nativeElement);