![](/img/trans.png)
[英]How to call a method in another component from material dialog component in angular 14
[英]How can I call another component function from Angular Material Dialog
我有 Angular 应用程序,我的列表数据组件上有一个预览弹出窗口,预览弹出窗口是一个对话框组件。
现在,当我单击列表中的按钮时,我传递列表项的 Id,对话框根据传递给它的 Id 显示来自对话框组件的数据。 现在我已经在对话框上设置了一些操作,比如 Mark as complete 它在对话框组件中调用 function 并更新数据库,现在我希望一旦数据库更新,我用最新数据刷新我的列表组件。
这是我的代码:
对话框组件或(TaskspopupviewpcComponent):
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Component, OnInit, Inject,SecurityContext} from '@angular/core';
import {TaskscalendarviewpcComponent} from '../taskscalendarviewpc/taskscalendarviewpc.component';
import { DialogService } from '../../../../shared/services/dialog.service';
import { MatDialog } from '@angular/material/dialog';
import { ITasks } from '../../../models/tasks.model';
import { TasksService } from '../../../services/tasks.service';
import { DomSanitizer } from '@angular/platform-browser'
import { formatDate } from '@angular/common';
//--------we add the router here for edit to redirect to edit form-----//
import { ActivatedRoute,Router } from '@angular/router';
export class TasksData {
constructor(public dynamicdata: string, public id: number, public action: string, public text: string, public type: string) {}
}
@Component({
selector: 'app-taskspopupviewpc',
templateUrl: './taskspopupviewpc.component.html',
styleUrls: ['./taskspopupviewpc.component.scss'],
//template:`<app-taskscalendarviewpc #component1></app-taskscalendarviewpc>`
})
export class TaskspopupviewpcComponent implements OnInit {
action;
close;
taskId: number;
taskResult;
type: string;
taskname;
category;
startdate;
enddate;
textContent;
textContent1;
editorReadSantStyle = {
height: '100px',
alignment:'MJ Selected-Quill'
};
constructor(
private _router:Router,
private _activatedRoute: ActivatedRoute,
public dialog: MatDialog,
private dialogService: DialogService,
private taskservice:TasksService,
public callRef: MatDialogRef<TaskspopupviewpcComponent>,
@Inject(MAT_DIALOG_DATA) public data: TasksData,
private sanitizer?: DomSanitizer,
) {
this.taskId = data.id;
this.action = data.action;
this.close = data.text;
this.type = data.type;
}
ngOnInit(): void {
this.getTaskById(this.taskId);
}
closeWindow(): void {
this.callRef.close(false);
}
getTaskById(id) {
this.taskservice.getTaskById(id,'/tasks/').subscribe(
(thetask: ITasks) => this.dispalyTask(thetask),
error => {
const res = this.dialogService.ErrorDialog('Server Error', 'Sorry, the system is unavailable at the moment.', 'Close', 'Try Again');
res.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.callNext(200);
}
});
}
);
}
dispalyTask(task: ITasks) {
this.taskResult = task[0];
console.log(this.taskResult);
this.taskId = task[0].TaskID;
this.taskname = task[0].TaskName;
this.category = task[0].CategoryName;
this.startdate = formatDate(task[0].StartDate,'yyyy-MM-dd','en_US');
this.enddate = formatDate(task[0].EndDate,'yyyy-MM-dd','en_US');
//---fore here we hide the description----//
//this.textContent = this.HTMLSant(task[0].Description);
}
HTMLSant(html:string){
return this.sanitizer.bypassSecurityTrustHtml(html);
}
markAsComplete(taskId){
console.log(taskId);
this.closeWindow();
if(taskId>0){
console.log('-----Update task-----');
const result = {"TaskID":taskId,"Status":true};
this.taskservice.updateStatus(result, taskId, '/tasks/updatestatus/').subscribe(
res => {
if (res) {
this.dialogService.MessageBox('Marked as Complete', 'X', 100, 'SuccessMessage');
//this.callNext(1000);
//this.refreshCalendar(100);
} else {
this.dialogService.MessageBox('Error updating record', 'X', 5000, 'ErrorMessage');
}
},
error => {
const res = this.dialogService.ErrorDialog(
'Server Error',
'Sorry, the system is unavailable at the moment.',
'Close',
'Try Again'
);
res.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.callNext(200);
}
});
}
);
}
}
editTask(taskId:number){
console.log(taskId);
this.closeWindow();
this._router.navigate(['./tasks/alltasks/addtask/',taskId]);
}
}
我的列表组件或(TaskscalendarviewpcComponent):
import {Component,ChangeDetectionStrategy,ViewChild,TemplateRef, OnInit} from '@angular/core';
import {startOfDay, endOfDay, subDays, addDays, endOfMonth, isSameDay, isSameMonth, addHours,} from 'date-fns';
import { Subject } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { CalendarEvent, CalendarEventAction, CalendarEventTimesChangedEvent, CalendarView,} from 'angular-calendar';
import { ITasks } from '../../../models/tasks.model';
import { TasksService } from '../../../services/tasks.service';
import { DialogService } from '../../../../shared/services/dialog.service';
import { MatDialog } from '@angular/material/dialog';
//import { CalendarEventActionsComponent } from 'angular-calendar/modules/common/calendar-event-actions.component';
import { TasksData, TaskspopupviewpcComponent } from '../taskspopupviewpc/taskspopupviewpc.component';
const colors: any = {
red: {
primary: '#ad2121',
secondary: '#FAE3E3',
},
blue: {
primary: '#1e90ff',
secondary: '#D1E8FF',
},
yellow: {
primary: '#e3bc08',
secondary: '#FDF1BA',
},
};
@Component({
selector: 'app-taskscalendarviewpc',
templateUrl: './taskscalendarviewpc.component.html',
styleUrls: ['./taskscalendarviewpc.component.scss'],
providers: [DialogService]
})
export class TaskscalendarviewpcComponent implements OnInit {
@ViewChild('modalContent', { static: true }) modalContent: TemplateRef<any>;
view: CalendarView = CalendarView.Month;
CalendarView = CalendarView;
viewDate: Date = new Date();
modalData: {
action: string;
event: CalendarEvent;
};
actions: CalendarEventAction[] = [
{
label: '<i class="fas fa-fw fa-pencil-alt"></i>',
a11yLabel: 'Edit',
onClick: ({ event }: { event: CalendarEvent }): void => {
this.handleEvent('Edited', event);
},
},
{
label: '<i class="fas fa-fw fa-trash-alt"></i>',
a11yLabel: 'Delete',
onClick: ({ event }: { event: CalendarEvent }): void => {
this.events = this.events.filter((iEvent) => iEvent !== event);
this.handleEvent('Deleted', event);
},
},
];
refresh: Subject<any> = new Subject();
events: CalendarEvent[] = [];
activeDayIsOpen: boolean = true;
constructor(
private modal: NgbModal,
public dialog: MatDialog,
private dialogService: DialogService,
private taskservice:TasksService) {}
ngOnInit(){
console.log('---------Hi call db-----');
this.getAllmyTasks();
}
getAllmyTasks(){
this.taskservice.getAllMyPendingTasks('/tasks/getallmypendingtasks').subscribe(
(myDbData: ITasks[]) => {
console.log(myDbData);
myDbData.forEach((item)=>{
this.events.push({
id:item.TaskID,
start:new Date(item.StartDate),
end:new Date(item.EndDate),
title:item.TaskName,
color: colors.yellow,
actions: this.actions
})
});
this.viewDate = new Date();
},
error => {
const res = this.dialogService.ErrorDialog('Server Error', 'Sorry, the system is unavailable at the moment.', 'Close', 'Try again');
res.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.callNext(200);
}
});
}
);
}
openPreview(action: string, event: CalendarEvent): void {
let id:number = Number(event.id);
const res = new TasksData('{data}', id, 'open', 'X', 'view');
const req = this.dialog.open(TaskspopupviewpcComponent, { data: res, panelClass: 'mj-preview-modal' });
req.afterClosed().subscribe(dataBox => {
if (dataBox) {
const data = dataBox;
}
});
}
//---------Calendar------------------------//
dayClicked({ date, events }: { date: Date; events: CalendarEvent[] }): void {
//--note this.viewDate is current date;
console.log(date);
if (isSameMonth(date, this.viewDate)) {
if (
(isSameDay(this.viewDate, date) && this.activeDayIsOpen === true) ||
events.length === 0
) {
this.activeDayIsOpen = false;
} else {
this.activeDayIsOpen = true;
}
this.viewDate = date;
}
}
eventTimesChanged({
event,
newStart,
newEnd,
}: CalendarEventTimesChangedEvent): void {
this.events = this.events.map((iEvent) => {
if (iEvent === event) {
return {
...event,
start: newStart,
end: newEnd,
};
}
return iEvent;
});
this.handleEvent('Dropped or resized', event);
}
handleEvent(action: string, event: CalendarEvent): void {
console.log(action);
console.log('--------xxx------');
console.log(event.id);
let TaskId = event.id;
this.modalData = { event, action };
this.modal.open(this.modalContent, { size: 'lg' });
}
addEvent(): void {
this.events = [
...this.events,
{
title: 'New event',
start: startOfDay(new Date()),
end: endOfDay(new Date()),
color: colors.red,
draggable: true,
resizable: {
beforeStart: true,
afterEnd: true,
},
},
];
}
deleteEvent(eventToDelete: CalendarEvent) {
this.events = this.events.filter((event) => event !== eventToDelete);
}
setView(view: CalendarView) {
this.view = view;
}
closeOpenMonthViewDay() {
this.activeDayIsOpen = false;
}
}
将对话框组件更改为服务并且它起作用了,这是工作代码:
import {Component,ChangeDetectionStrategy,ViewChild,TemplateRef, OnInit} from '@angular/core';
import {startOfDay, endOfDay, subDays, addDays, endOfMonth, isSameDay, isSameMonth, addHours,} from 'date-fns';
import { Subject } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { CalendarEvent, CalendarEventAction, CalendarEventTimesChangedEvent, CalendarView,} from 'angular-calendar';
import { ITasks } from '../../../models/tasks.model';
import { TasksService } from '../../../services/tasks.service';
import { DialogService } from '../../../../shared/services/dialog.service';
import { MatDialog } from '@angular/material/dialog';
//import { CalendarEventActionsComponent } from 'angular-calendar/modules/common/calendar-event-actions.component';
import { TasksData, TaskspopupviewpcComponent } from '../taskspopupviewpc/taskspopupviewpc.component';
import {TasksdialogService} from '../../../services/tasksdialog.service';
const colors: any = {
red: {
primary: '#ad2121',
secondary: '#FAE3E3',
},
blue: {
primary: '#1e90ff',
secondary: '#D1E8FF',
},
yellow: {
primary: '#e3bc08',
secondary: '#FDF1BA',
},
};
@Component({
selector: 'app-taskscalendarviewpc',
templateUrl: './taskscalendarviewpc.component.html',
styleUrls: ['./taskscalendarviewpc.component.scss'],
providers: [DialogService,TasksdialogService]
})
export class TaskscalendarviewpcComponent implements OnInit {
@ViewChild('modalContent', { static: true }) modalContent: TemplateRef<any>;
view: CalendarView = CalendarView.Month;
CalendarView = CalendarView;
viewDate: Date = new Date();
modalData: {
action: string;
event: CalendarEvent;
};
actions: CalendarEventAction[] = [
{
label: '<i class="fas fa-fw fa-pencil-alt"></i>',
a11yLabel: 'Edit',
onClick: ({ event }: { event: CalendarEvent }): void => {
this.handleEvent('Edited', event);
},
},
{
label: '<i class="fas fa-fw fa-trash-alt"></i>',
a11yLabel: 'Delete',
onClick: ({ event }: { event: CalendarEvent }): void => {
this.events = this.events.filter((iEvent) => iEvent !== event);
this.handleEvent('Deleted', event);
},
},
];
refresh: Subject<any> = new Subject();
events: CalendarEvent[] = [];
activeDayIsOpen: boolean = true;
constructor(
private modal: NgbModal,
public dialog: MatDialog,
private dialogService: DialogService,
private taskDialogService: TasksdialogService,
private taskservice:TasksService) {}
ngOnInit(){
console.log('---------Hi call db-----');
this.getAllmyTasks();
}
getAllmyTasks(){
this.taskservice.getAllMyPendingTasks('/tasks/getallmypendingtasks').subscribe(
(myDbData: ITasks[]) => {
console.log(myDbData);
myDbData.forEach((item)=>{
this.events.push({
id:item.TaskID,
start:new Date(item.StartDate),
end:new Date(item.EndDate),
title:item.TaskName,
color: colors.yellow,
actions: this.actions
})
});
this.viewDate = new Date();
},
error => {
const res = this.dialogService.ErrorDialog('Server Error', 'Sorry, the system is unavailable at the moment.', 'Close', 'Try again');
res.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.callNext(200);
}
});
}
);
}
setStatusToComplete(action: string, event: CalendarEvent){
let id:number = Number(event.id);
const result = this.taskDialogService.openTasksDialog('',id,'myaction','Are you sure','mytype');
result.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.deleteTaskById(TaskID);
console.log('---------h--------dialog-----');
this.markAsComplete(id);
}
});
}
markAsComplete(taskId){
console.log(taskId);
if(taskId>0){
console.log('-----Update task-----');
const result = {"TaskID":taskId,"Status":true};
this.taskservice.updateStatus(result, taskId, '/tasks/updatestatus/').subscribe(
res => {
if (res) {
this.dialogService.MessageBox('Marked as Complete', 'X', 100, 'SuccessMessage');
//this.callNext(1000);
//this.refreshCalendar(100);
this.events = [];
this.getAllmyTasks();
} else {
this.dialogService.MessageBox('Error updating record', 'X', 5000, 'ErrorMessage');
}
},
error => {
const res = this.dialogService.ErrorDialog(
'Server Error',
'Sorry, the system is unavailable at the moment.',
'Close',
'Try Again'
);
res.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.callNext(200);
}
});
}
);
}
}
openPreview(action: string, event: CalendarEvent): void {
let id:number = Number(event.id);
const res = new TasksData('{data}', id, 'open', 'X', 'view');
const req = this.dialog.open(TaskspopupviewpcComponent, { data: res, panelClass: 'mj-preview-modal' });
req.afterClosed().subscribe(dataBox => {
if (dataBox) {
const data = dataBox;
}
});
}
//---------Calendar------------------------//
dayClicked({ date, events }: { date: Date; events: CalendarEvent[] }): void {
//--note this.viewDate is current date;
console.log(date);
if (isSameMonth(date, this.viewDate)) {
if (
(isSameDay(this.viewDate, date) && this.activeDayIsOpen === true) ||
events.length === 0
) {
this.activeDayIsOpen = false;
} else {
this.activeDayIsOpen = true;
}
this.viewDate = date;
}
}
eventTimesChanged({
event,
newStart,
newEnd,
}: CalendarEventTimesChangedEvent): void {
this.events = this.events.map((iEvent) => {
if (iEvent === event) {
return {
...event,
start: newStart,
end: newEnd,
};
}
return iEvent;
});
this.handleEvent('Dropped or resized', event);
}
handleEvent(action: string, event: CalendarEvent): void {
console.log(action);
console.log('--------xxx------');
console.log(event.id);
let TaskId = event.id;
this.modalData = { event, action };
this.modal.open(this.modalContent, { size: 'lg' });
}
addEvent(): void {
this.events = [
...this.events,
{
title: 'New event',
start: startOfDay(new Date()),
end: endOfDay(new Date()),
color: colors.red,
draggable: true,
resizable: {
beforeStart: true,
afterEnd: true,
},
},
];
}
deleteEvent(eventToDelete: CalendarEvent) {
this.events = this.events.filter((event) => event !== eventToDelete);
}
setView(view: CalendarView) {
this.view = view;
}
closeOpenMonthViewDay() {
this.activeDayIsOpen = false;
}
}
您可以创建service
,然后在该service
中编写 function ,您可以在任何component
中调用它..
您可以从这些链接中获得有关如何创建service
以及如何使用它的完美信息。
https://www.tutorialspoint.com/angular4/angular4_services.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.