从angularjs迁移到Angular 14



我正在从Angularjs 1迁移我的应用程序。到Angular 14时,遇到了一个与可重用的模态弹出(这个模态弹出显示了带有ok/cancel按钮的消息)相关的问题。下面是用controller编写的Angularjs代码,

$rootScope.showConfirmModal = function (message, callback) {
var modalHtml = '<div class="modal-header"><h3 class="modal-title" id="modal-title">Warning!</h3></div>' +
'<div class="modal-body">' + message + '</div>';
modalHtml += '<div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button>' +
'<button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>';
var modalInstance = $modal.open({
template: modalHtml,
controller: function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close();
callback(true);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
callback(false);
};
}
});
}
在angularjs 1的大部分地方都调用了上面的模态弹出。x应用程序。现在,如何把它移动到Angular 14中呢?

请帮助或建议我与任何示例代码,不确定是否写作为组件或指令。

下面是类似的例子。创建组件:

import { Component } from '@angular/core';
import { ModalDialogService } from './modal-dialog.service';
@Component({
selector: 'app-modal-dialog',
templateUrl: './modal-dialog.component.html',
styleUrls: ['./modal-dialog.component.scss'],
})
export class ModalDialogComponent {
config: any = null;
constructor(private modalDialogService: ModalDialogService) {}
ngOnInit() {
this.config = null;
this.modalDialogService.show = this.show.bind(this);
}
show(config: any) {
this.config = config;
}
onConfirm() {
if (this.config && this.config.onConfirm) {
this.config.onConfirm();
}
this.config = null;
}
onCancel() {
if (this.config && this.config.onCancel) {
this.config.onCancel();
}
this.config = null;
}
}

与HTML:

<div class="modal-dialog fk-modal-dismissable" *ngIf="config">
<div class="modal-dialog-wrapper">
<div class="modal-dialog-header-wrapper">
<span class="modal-dialog-header-text" *ngIf="config.headerText">
{{ config.headerText }}
</span>
</div>
<div class="modal-dialog-body-wrapper">
<span class="modal-dialog-body-text">
{{ config.bodyText || 'Are you sure?' }}
</span>
</div>
<div class="modal-dialog-action-wrapper">
<button class="btn2 modal-dialog-action" (click)="onCancel()">
{{ config.cancelText || 'Cancel' }}
</button>
<button class="btn2 modal-dialog-action" (click)="onConfirm()">
{{ config.confirmText || 'Confirm' }}
</button>
</div>
</div>
</div>

使用service显示弹出窗口:

import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ModalDialogService {
constructor() {
}
show(config: any) {
// implementation of function is declared in modal dialog component 
}
}

在app主html页面上使用组件,让它在所有的路由上都能工作。

完整的工作示例在这里:https://stackblitz.com/edit/angular-ivy-4qzkh7?file=src/app/modal-dialog.service.ts

运行程序:https://angular-ivy-4qzkh7.stackblitz.io

最新更新