简体   繁体   中英

How can I call another component function from Angular Material Dialog

I have Angular Application, I have a preview popup on my list data component the preview popup is a dialog component.

now when I click on button from my list I pass Id of list item, the dialogs display data from dialog component based on the Id passed to it. now I have set some actions on the dialog like Mark as complete it calls a function in dialog component and updates the database, now I want once the database updated, I refresh my list component with latest data.

here is my code:

dialog component or (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]);
        }


      }

my list component or (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;
        }

        
      }

在此处输入图像描述

Change dialog component as a Service and it worked, here is the working code:

          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;
      }

      
    }

You can create service and then write function in that service and you can call it in any component ..

you can get perfect information about How to create service and How to use it from these links..

https://www.tutorialspoint.com/angular4/angular4_services.htm

https://angular.io/tutorial/toh-pt4

https://angular.io/guide/architecture-services

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM