我目前正在使用ngx-formly从JSON动态创建一堆Angular表单,这非常好用。我有一个特殊的用例,表单上的自定义按钮应该打开一个包含另一个表单的模式对话框,其中还包含使用ngx-formly创建的表单。我在ngx-formly网站上看到的示例使用自定义按钮,并使用.ts文件创建自定义组件,但我想避免这种情况,因为我会有几个表单执行此操作,并且我不想创建不同的组件对此。
有没有办法从ngx-formly形式触发模态对话框,用ngx-formly形式显示模态,而不必为它们创建多个组件(.ts)文件?
答案 0 :(得分:0)
<强> modal.service.ts 强>
import {Injectable} from '@angular/core';
import {ModalModel} from './modal.model';
import {Subject} from "rxjs/Subject";
declare let $: any;
@Injectable()
export class ModalService {
modalData = new Subject<ModalModel>();
modalDataEvent = this.modalData.asObservable();
open(modalData: ModalModel) {
this.modalData.next(modalData);
$('#myModal').modal('show');
}
}
<强> modal.component.ts 强>
import { Component } from '@angular/core';
import { ModalService } from './modal.service';
import {ModalModel} from './modal.model';
declare let $: any;
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: [ './modal.component.css' ]
})
export class ModalComponent {
modalData: ModalModel;
constructor(private modalService: ModalService) {
this.modalService.modalDataEvent.subscribe((data) => {
this.modalData = data;
})
}
}
从任何组件调用此服务
import { Component } from '@angular/core';
import { ModalService } from '../modal/modal.service';
import { ModalModel } from '../modal/modal.model';
declare let $: any;
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: [ './home.component.css' ]
})
export class HomeComponent {
modelData = new ModalModel();
constructor(private modalService: ModalService) {
}
open() {
this.modelData.header = 'This is my dynamic HEADER from Home component';
this.modelData.body = 'This is my dynamic BODY from Home component';
this.modelData.footer = 'This is my dynamic footer from Home component';
this.modalService.open(this.modelData);
}
}