【问题标题】:How to combine (compile) modal dialog from separate components Angular 2 dynamically?如何动态组合(编译)来自不同组件Angular 2的模态对话框?
【发布时间】:2017-05-12 18:15:23
【问题描述】:

我正在开发带有模态对话框的 Angular 2 + TypeScript 应用程序。

我有主要的模态组件:

<div class="modal">
    <div class="header">{{title}}</div>
    <div class="body">{{body}}</div>
    <div class="footer">{{footer}}</div>
</div>

其中{{title}} - 文本,{{body}}{{footer}} - 来自不同组件的 html。

在包含打开模式对话框的按钮的组件中,我有这个:

import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { ModalComponent } from './modal.component';
import { BodyOneComponent } from './body/body-one.component';
import { FooterOneComponent } from './footer/footer-one.component';

@Component({
    selector: 'ac-parent',
    templateUrl: './app/parent.component.html'
})
export class ParentComponent {
    constructor(private modalService: NgbModal) { }

    openModal() {
        const modalRef = this.modalService.open(ModalComponent);
        modalRef.componentInstance.title = "Modal title";
        modalRef.componentInstance.body = "get html from BodyOneComponent somehow";
        modalRef.componentInstance.footer = "get html from FooterOneComponent somehow";
    }
}

那么,我的问题是如何从其他组件获取组件的 html 内容?以及如何将这些 html 编译成一个视图? 这样做的最佳方法是什么?我应该使用与模板表达式不同的东西吗?

【问题讨论】:

标签: angular typescript


【解决方案1】:

model.ts 单独组合

<div class="modal">
    <div class="header">{{title}}</div>
    <div class="body">{{body}}</div>
    <div class="footer">{{footer}}</div>
</div>

组件是

import { Component, Input } from '@angular/core';

@Component({
  selector: 'model-app',
  template: '<h1>Model {{major}}</h1>',
})
export class ModelComponent  { 
@Input() major: number = 10;
name = 'Angular'; 

}

父组合传递major的值

import { Component, Output } from '@angular/core';

@Component({
  selector: 'my-app',
  template: '<h1>Hello {{name}}</h1> <model-app></model-app>',
})
export class AppComponent  { 

    name = 'Angular'; 
}

【讨论】:

    【解决方案2】:

    您可以使用ng-content。如果你熟悉 angular 1,它类似于嵌入。

    在您的主模式中,您可以执行以下操作:-

    <div class="modal">
        <div class="header">
           <ng-content select="[m-header]"></ng-content>
        </div>
        <div class="body">
           <ng-content select="[m-body]"></ng-content>
        </div>
        <div class="footer">
           <ng-content select="[m-footer]"></ng-content>
        </div>
    </div>
    

    然后在你的父组件中,你可以这样使用它:-

    <h1>Hello {{name}}</h1> 
    <modal>
        <div m-header>
           Your title here
        </div>
        <div m-body>
          <p>Your html content here</p>
        </div>
    </modal>
    

    请参阅我的文章中的详细信息。 https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

    【讨论】:

      猜你喜欢
      • 2011-02-01
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2022-11-25
      • 2017-09-02
      • 2017-10-18
      • 1970-01-01
      相关资源
      最近更新 更多