【问题标题】:Angular2 - Component into dynamically created elementAngular2 - 组件到动态创建的元素中
【发布时间】:2016-12-01 23:22:43
【问题描述】:

我使用 google maps javascript api,我必须在 InfoWindow 中显示一个 Angular 组件。

在我的项目中,我使用 Jsonp 服务加载了谷歌地图 API。比我有可用的google.maps.Map 对象。稍后在一个组件中,我创建了一些标记并为它们附加了一个点击监听器:

TypeScript:

let marker = new google.maps.Marker(opts);
marker.setValues({placeId: item[0]});
marker.addListener('click', (ev: google.maps.MouseEvent) => this.onMarkerClick(marker, ev));

然后在 click 处理程序中,我想打开一个包含 Angular 组件的信息窗口:

TypeScript:

private onMarkerClick(marker: google.maps.Marker, ev: google.maps.MouseEvent) {

    var div = document.createElement();
    this.placeInfoWindow.setContent(div);
    // Magic should happen here somehow
    // this.placeInfoWindow.setContent('<app-info-view-element></app-info-view-element>');
    this.placeInfoWindow.open(this.map, marker);
}

我最终做的是一些普通的 JS:

TypeScript:

 private onMarkerClick(marker: google.maps.Marker, ev: google.maps.MouseEvent) {


    let div = document.createElement('div');
    div.className = 'map-info-window-container';
    div.style.height = '140px';
    div.style.width = '240px';

    this.placeInfoWindow.setContent(div);

    this.placeInfoWindow.open(this.map, marker);
    this.placesService.getPlace(marker.get('id')).subscribe(res => {
      this.decorateInfoWindow(div, res.name, marker);
    }, error => {
      this.decorateInfoWindow(div, ':( Failed to load details: ', marker);
    });

  }



private decorateInfoWindow(containerEl: HTMLElement, title?:string, marker?:google.maps.Marker) {
    let h3 = document.createElement('h3');
    h3.innerText = title;
    containerEl.appendChild(h3);

    let buttonBar = document.createElement('div');
    let editButton = document.createElement('button')
    editButton.innerText = "Edit";
    editButton.addEventListener('click', ev => {
      this.editPlace(marker);
    });
    buttonBar.appendChild(editButton);
    containerEl.appendChild(buttonBar);
  }

据我所知,问题是创建动态组件的唯一可行方法是使用 Angulars ViewContainerRef:

但没有文档或示例描述如何从动态创建的元素创建ViewContainerRef。


是否可以强制框架以某种方式处理 DOM?正如在很多线程中所说:“Angular 不处理 innerHTML 或 appendChild”。这是一个彻底的死胡同吗?

第二:是否可以使用Renderer 实现? (不熟悉),我看到了这个Canvas Renderer Experiment,理论上,我想它也适用于谷歌地图,因为我们可以推断地图只是一种特殊的画布。它在上一个版本中仍然可用还是已更改? DomRenderer 不在文档中,但可以在源代码中找到。

【问题讨论】:

    标签: google-maps angular


    【解决方案1】:

    这里的主要规则是动态创建组件需要获取其工厂。

    1) 将动态组件添加到entryComponents 数组中,除了包含到declarations 中:

    @NgModule({
      ...
      declarations: [ 
        AppInfoWindowComponent,
        ...
      ],
      entryComponents: [
        AppInfoWindowComponent,
        ...
      ],
    })
    

    这是 Angular 编译器为组件生成 ngfactory 的提示,即使我们不直接在某些模板中使用我们的组件。

    2) 现在我们需要将ComponentFactoryResolver 注入到我们想要获取ngfactory 的组件/服务中。你可以把ComponentFactoryResolver想象成一个组件工厂的仓库

    app.component.ts

    import { ComponentFactoryResolver } from '@angular/core'
    ...
    constructor(private resolver: ComponentFactoryResolver) {}
    

    3) 是时候获取AppInfoWindowComponent factory:

    const compFactory = this.resolver.resolveComponentFactory(AppInfoWindowComponent);
    this.compRef = compFactory.create(this.injector);
    

    4) 有了工厂,我们可以随意使用它。以下是一些案例:

    • ViewContainerRef.createComponent(componentFactory,...) 在 vi​​ewContainer 旁边插入组件。

    • ComponentFactory.create(injector, projectableNodes?, rootSelectorOrNode?) 只是创建组件,这个组件可以插入到匹配rootSelectorOrNode的元素中

    注意,我们可以在ComponentFactory.create函数的第三个参数中提供节点或选择器。在许多情况下它可能会有所帮助。在这个例子中,我将简单地创建组件,然后插入到某个元素中。

    onMarkerClick 方法可能如下所示:

    onMarkerClick(marker, e) {
      if(this.compRef) this.compRef.destroy();
    
      // creation component, AppInfoWindowComponent should be declared in entryComponents
      const compFactory = this.resolver.resolveComponentFactory(AppInfoWindowComponent);
      this.compRef = compFactory.create(this.injector);
    
      // example of parent-child communication
      this.compRef.instance.param = "test";
      const subscription = this.compRef.instance.onCounterIncremented.subscribe(x => { this.counter = x; });  
    
      let div = document.createElement('div');
      div.appendChild(this.compRef.location.nativeElement);
    
      this.placeInfoWindow.setContent(div);
      this.placeInfoWindow.open(this.map, marker);
    
      // 5) it's necessary for change detection within AppInfoWindowComponent
      // tips: consider ngDoCheck for better performance
      this.appRef.attachView(this.compRef.hostView);
      this.compRef.onDestroy(() => {
        this.appRef.detachView(this.compRef.hostView);
        subscription.unsubscribe();
      });
    }
    

    5) 不幸的是,动态创建的组件不是变更检测树的一部分,因此我们还需要注意变更检测。它可以通过使用ApplicationRef.attachView(compRef.hostView) 来完成,正如上面示例中所写的那样,或者我们可以明确地使用我们正在创建动态组件的组件的ngDoCheck(example) 来完成(在我的情况下为AppComponent)

    app.component.ts

    ngDoCheck() {
      if(this.compRef) {
        this.compRef.changeDetectorRef.detectChanges()
      }
    }
    

    这种方法更好,因为它只会在当前组件更新时更新动态组件。另一方面,ApplicationRef.attachView(compRef.hostView) 将更改检测器添加到更改检测器树的根,因此它将在每个更改检测滴答时调用。

    Plunker Example


    提示:

    因为addListener 在 angular2 区域外运行,我们需要在 angular2 区域内显式运行我们的代码:

    marker.addListener('click', (e) => { 
      this.zone.run(() => this.onMarkerClick(marker, e));
    });
    

    【讨论】:

    • 很高兴听到:)
    • @Jigar 你能提供一个plunker吗?
    • @yurzui;很抱歉发表评论,更改检测也在起作用。
    • @MichalMoravcik 是的,确实如此
    • @yurzui,非常感谢,我一定会试一试,看起来很有希望
    猜你喜欢
    • 2018-05-31
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 2021-12-06
    • 2017-07-21
    • 1970-01-01
    • 2016-12-07
    • 2017-11-01
    相关资源
    最近更新 更多