如何动态创建自举模式作为Angular2组件?

时间:2016-04-12 07:42:00

标签: angular

原始标题:无法在Angular 2中初始化动态追加(HTML)组件

我已经创建了一个指令,在初始化时将一个模态附加到正文。当单击一个按钮(带有指令注入其中)时,这个模态会激活。但我希望这个模态的内容是另一个组件(实际上我希望模态是组件)。我似乎无法初始化组件。

以下是我所做过的事情:

http://plnkr.co/edit/vEFCnVjGvMiJqb2Meprr?p=preview

我试图让my-comp成为我的组件的模板

 '<div class="modal-body" #theBody>' 
            + '<my-comp></my-comp>' + 
 '</div>

1 个答案:

答案 0 :(得分:11)

更新2.0.0最终

Plunker example >= 2.0.0

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, ModalComponent, CompComponent],
  providers: [SharedService],
  entryComponents: [CompComponent],
  bootstrap: [ App, ModalComponent ]
})
export class AppModule{}
export class ModalComponent {
  @ViewChild('theBody', {read: ViewContainerRef}) theBody;

  cmp:ComponentRef;

  constructor(
    sharedService:SharedService, 
    private componentFactoryResolver: ComponentFactoryResolver, 
    injector: Injector) {

    sharedService.showModal.subscribe(type => {
      if(this.cmp) {
        this.cmp.destroy();
      }
      let factory = this.componentFactoryResolver.resolveComponentFactory(type);
      this.cmpRef = this.theBody.createComponent(factory)
      $('#theModal').modal('show');
    });
  }

  close() {
    if(this.cmp) {
      this.cmp.destroy();
    }
    this.cmp = null;
  }
}

<强>提示

如果一个应用程序更改SharedService中的状态或调用导致Observable发出值的方法,并且订阅者位于不同的应用程序然后是发射器,则执行订户中的代码在发射器的NgZone中。

因此,在SharedService使用

订阅观察者时
class MyComponent {
  constructor(private zone:NgZone, private sharedService:SharedService) {
    private sharedService.subscribe(data => this.zone.run() => {
      // event handler code here
    });
  }
}

有关如何触发更改检测的更多详细信息,请参阅Triggering Angular2 change detection manually

<强>原始

Angular不会处理动态添加的HTML,也不会导致实例化或添加组件或指令。

您无法使用 DynamicComponentLoader (已弃用)ViewContainerRef.createComponent() bootstrap()Angular 2 dynamic tabs with user-click chosen components)在Angulars根组件(AppComponent)之外添加组件。

我想最好的方法是在Angulars根组件之外创建第二个组件,在每个组件上调用var sharedService = new SharedService(); bootstrap(AppComponent, [provide(SharedService, {useValue: sharedService})]); bootstrap(ModalComponent, [provide(SharedService, {useValue: sharedService})]); 并使用共享服务进行通信:

@Injectable()
export class SharedService {
  showModal:Subject = new Subject();
}

@Component({
  selector: 'comp-comp',
  template: `MyComponent`
})
export class CompComponent { }


@Component({
  selector: 'modal-comp',
  template: `
  <div class="modal fade" id="theModal" tabindex="-1" role="dialog" aria-labelledby="theModalLabel">
    <div class="modal-dialog largeWidth" role="document">
      <div class="modal-content">
        <div class="modal-header">
        <h4 class="modal-title" id="theModalLabel">The Label</h4></div>
        <div class="modal-body" #theBody>
      </div>
    <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal" (close)="close()">Close</button>
  </div></div></div></div>
`
})
export class ModalComponent {
  cmp:ComponentRef;
  constructor(sharedService:SharedService, dcl: DynamicComponentLoader, injector: Injector, elementRef: ElementRef) {
    sharedService.showModal.subscribe(type => {
      if(this.cmp) {
        this.cmp.dispose();
      }
      dcl.loadIntoLocation(type, elementRef, 'theBody')
      .then(cmp => {
        this.cmp = cmp;
        $('#theModal').modal('show');
      });
    });
  }

  close() {
    if(this.cmp) {
      this.cmp.dispose();
    }
    this.cmp = null;
  }
}


@Component({
  selector: 'my-app',
  template: `
<h1>My First Attribute Directive</h1>
<button (click)="showDialog()">show modal</button>
<br>
<br>`,
})
export class AppComponent {
  constructor(private sharedService:SharedService) {}

  showDialog() {
    this.sharedService.showModal.next(CompComponent);
  }
}

Plunker example beta.17
Plunker example beta.14

bash -i -c "trap ' ' SIGINT; tail -F '$1'; trap - SIGINT"