首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ionic 2-从简单的angular 2组件创建模式(不创建与ionic NavParams和NavController的耦合)

Ionic 2-从简单的angular 2组件创建模式(不创建与ionic NavParams和NavController的耦合)
EN

Stack Overflow用户
提问于 2016-08-16 00:09:31
回答 1查看 811关注 0票数 1

所有内容都在标题中。

我想从我的常规angular 2组件创建模态。问题是,我们需要注入NavParams来检索参数,注入NavController来关闭模型。

谢谢

编辑:我已经发布了一个答案,但也许有更好的答案。再次感谢。

EN

回答 1

Stack Overflow用户

发布于 2016-08-16 00:42:45

一种可能的解决方案是创建一个通用包装器作为模态,它将实例化卷筒组件。

我使用了这个链接:Is it possible to manually instantiate component in angular 2

下面是我用来创建模式的代码:

代码语言:javascript
复制
    let modal = this.modalController.create(ModalWrapper, {
      type: MyAngular2SimpleComponent,
      init: function (component) {
        component.input1 = argument1;
        component.input2 = argument2;
      }
    });
    modal.onDidDismiss(data => {
      console.log(data);
    });
    modal.present();

我的角度组件:

代码语言:javascript
复制
@Component({
    template: `{{input1}} and {{input2}}`
})
export class MyAngular2SimpleComponent {
    @Input() input1;
    @Input() input2;
}

模式包装器:

代码语言:javascript
复制
@Component({
  template: `
    <div #target></div>
  `
})
export class ModalWrapper {

  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;

  componentRef:ComponentRef<any>;
  private isViewInitialized:boolean = false;

  constructor(private resolver:ComponentResolver, private params:NavParams) {
    this.type = params.get('type');
  }

  ngOnInit() {

  }

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.componentRef) {
      this.componentRef.destroy();
    }
    this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.componentRef = this.target.createComponent(factory);

      // to access the created instance use
      // this.compRef.instance.someProperty = 'someValue';
      // this.compRef.instance.someOutput.subscribe(val => doSomething());
      this.params.get('init')(this.componentRef.instance);
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();
  }

  ngOnDestroy() {
    if(this.componentRef) {
      this.componentRef.destroy();
    }
  }
}

包装器中的主要内容是:

代码语言:javascript
复制
this.params.get('init')(this.componentRef.instance);

我调用了在创建模型时传入参数的init方法。允许填充数据的某种双重调度。

感谢Günter Zöchbauer

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38958734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档