Home > other >  calling one method from one component to another component
calling one method from one component to another component

Time:12-13

assignToAll method is in EmployeeComponent but need to call it from AssignCourseComponent how can achieve that

assigncourse.ts:

import { Component, HostListener, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { EmployeeComponent } from '../employee/employee.component';
import { AssignCourse } from '../interface/assigncourse';
import { Employee, SortedList } from '../interface/employee';

import { AssignCoursesService } from '../service/assigncourse.service';

@Component({
  selector: 'app-assigncourse',
  templateUrl: './assigncourse.component.html',
  styleUrls: ['./assigncourse.component.css'],
  providers: [AssignCoursesService],
})
export class AssigncourseComponent implements OnInit {
 assignCourse: Array<AssignCourse>;
  employeeList: SortedList = {
    sortedList: new Array<Employee>(),
  };
  searchText: string = '';

  constructor(
    private assignCourseService: AssignCoursesService,
    private modalService: NgbModal,
    public dialog: MatDialog
  ) {
    this.assignCourse = new Array<AssignCourse>();
  }
  @HostListener('document:keyup', ['$event'])
  handleKeydown(event: KeyboardEvent) {
    if (event.keyCode === 8) {
      console.log('checking');
      event.preventDefault;
      event.stopPropagation;
    }
  }

  
  ngOnInit(): void {
    this.getAllCourses();
    // this.getAllEmployees();
    
  }
  getAllCourses() {
    this.assignCourseService.getAllCourses().subscribe((data) => {
      this.assignCourse = data;
      console.log(this.assignCourse);
    });
  }

  getAllEmployees(courseId: Number) {
    // const empDetails = '46092955/' courseId;
    const empDetails = '46113588/'   courseId;
    this.assignCourseService.getAllEmployee(empDetails).subscribe((data) => {
      this.employeeList = data;
      console.log(this.employeeList);
    });
  }

  search() {
    if (this.searchText != '') {
      this.employeeList.sortedList = this.employeeList.sortedList.filter(
        (res) => {
          return res.fullName
            .toLocaleLowerCase()
            .match(this.searchText.toLocaleLowerCase());
        }
      );
    } else if (this.searchText == '') {
      this.ngOnInit();
    }
  }

  openDialog(courseId: Number) {
    console.log(courseId);
    this.dialog.open(EmployeeComponent, { data: { courseId: courseId } });
    
  }
}

when click on Assign All it should render EmployeeComponent 's assignToEmployees() method

AssignCourse.html

<div >
  <table >
    <thead>
      <tr>
        <th scope="col">S.No</th>
        <th scope="col">Name Of Course</th>
        <th scope="col">Training Platform</th>
        <th scope="col">Course Url</th>
        <th scope="col">Assign to</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let course of assignCourse">
        <th scope="row">{{ course.courseId }}</th>
        <td>{{ course.courseName }}</td>
        <td>{{ course.trainingPlatform }}</td>
        <td>{{ course.courseUrl }}</td>
        <td>
          <button mat-button (click)="openDialog(course.courseId)">
            <i  aria-hidden="true"></i>
          </button>
    <div > 
  
  <button
    type="button"
    
    data-bs-toggle="modal"
    data-bs-target="#exampleModal"
    (click)="openDialog()"
    
  >
    Assign All
  </button>
</div>
        </td>
      </tr>
    </tbody>
  </table>
</div> 

this is employee.component.ts where AssignToAll method is implemented

import { Component, Inject,OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Assign } from '../interface/assign';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Employee, SortedList } from '../interface/employee';
import { AssignCoursesService } from '../service/assigncourse.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css'],
  providers: [AssignCoursesService],
})
export class EmployeeComponent implements OnInit {
  // @Input() courseId: Number;

  employeeList: SortedList = {
    sortedList: new Array<Employee>(),
  };
  searchText: string = '';
  assignList: Assign = {
    courseId: 0,
    userIds: new Array<number>(),
    endDate: new Date(),
    managerId: 0,
  };
  minDate: any = '';
  dateFormat: Date = this.assignList.endDate;
  condition2: boolean;
  constructor(
    private assignCourseService: AssignCoursesService,
    private snackBar: MatSnackBar,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {}

  ngOnInit(): void {
    setTimeout(() => {
      this.ngOnInit();
    }, 1000 * 10);
    this.getDate();
    this.getAllEmployees(this.data.courseId);
    this.assignList.courseId = this.data.courseId;
  }

  getAllEmployees(courseId: Number) {
    const empDetails = '46113588/'   courseId;
    this.assignCourseService.getAllEmployee(empDetails).subscribe((data) => {
      this.employeeList = data;
      console.log(this.employeeList);
    });
  }
  search() {
    if (this.searchText != '') {
      this.employeeList.sortedList = this.employeeList.sortedList.filter(
        (res) => {
          return res.fullName
            .toLocaleLowerCase()
            .match(this.searchText.toLocaleLowerCase());
        }
      );
    } else if (this.searchText == '') {
      this.ngOnInit();
    }
  }
  addEmployees(userIds: number, managerId: number) {
    if (this.assignList.userIds.includes(userIds)) {
      const indexx = this.assignList.userIds.indexOf(userIds);
      this.assignList.userIds.splice(indexx, 1);
    } else {
      this.assignList.userIds.push(userIds);
    }

    this.assignList.managerId = managerId;
    console.log(this.assignList);
  }

  openSnackBar(message: string, action: string) {
    if (action == 'Done') {
      this.snackBar.open(message, action, {
        duration: 5000,
        panelClass: ['mat-success'],
        verticalPosition: 'top',
      });
    } else {
      this.snackBar.open(message, action, {
        duration: 5000,
        verticalPosition: 'top',
      });
    }
  }
  getDate() {
    var date: any = new Date();
    var toDate: any = date.getDate();
    if (toDate < 10) {
      toDate = '0'   toDate;
    }
    var month = date.getMonth()   1;
    if (month < 10) {
      month = '0'   month;
    }
    var year = date.getFullYear();
    this.minDate = year   '-'   month   '-'   toDate;
    console.log(this.minDate);
  }
  assignToEmployees() {
    if (this.assignList.endDate == this.dateFormat) {
      this.openSnackBar('Add an Expected EndDate', 'Error');
    } else {
      if (this.assignList.userIds.length != 0) {
        this.assignCourseService
          .addCourseToEmployee(this.assignList)
          .subscribe((datas) => {
            console.log(datas);
            this.assignList.userIds = new Array<number>();
          });
        this.openSnackBar('Course Added Successfully', 'Done');
      }
    }
  }
  assignToAll() {
    // if(this.condition2==false){ not require
    this.assignList.userIds = this.employeeList.sortedList.filter(i=>i.assigned==false).map((item) => {
     return item.empId;
    });
    this.condition2 = true;
    this.assignList.managerId = this.employeeList.sortedList[0].n1EmpId;
    this.assignToEmployees();
    // console.log(this.assignList.userIds)--not require
    // }else{
    //   this.assignList.userIds=[];
    //   this.condition2=false;
    // }--not require
  }
}

CodePudding user response:

Yo can not do that. Because components have their scope and you can't access their methods. What you can do is:

  1. Create a service with ng g s shared-functions.

  2. Define your function there.

  3. Instantiate it in both components.

  4. Use them in both components. :)

CodePudding user response:

share-data.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ShareDataService {

  constructor() { }

  shareFunction = () => {
    console.log("sharing data....");
  }
}

component1.ts

import { Component, OnInit } from '@angular/core';
import { ShareDataService } from '../services/share-data.service'; //import service

@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.scss']
})
export class Component1Component implements OnInit {

  constructor(
    private shareDataService: ShareDataService // dependency injection
  ) { }

  called: boolean = false;

  ngOnInit(): void {
    this.called = true;

    this.shareDataService.shareFunction(); // Shared function 
  }
}

component2.ts

import { Component, OnInit } from '@angular/core';
import { ShareDataService } from '../services/share-data.service'; //import service

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.scss']
})
export class Component2Component implements OnInit {

  constructor(
    private shareDataService: ShareDataService // dependency injection
  ) { }

  called: boolean = false;

  ngOnInit(): void {
    this.called = true;

    this.shareDataService.shareFunction(); // Shared function 
  }
}

CodePudding user response:

Generally, for solving more complex problems, the below design pattern is recommended. The following methods are sample.

@Injectable({
  providedIn: 'root'
})
export class ShareService {

  private _Subject = new BehaviorSubject<boolean>(false);
  public _observer$:Observable<boolean> = this._Subject.asObservable();

  constructor() { }

  start() {
    this._Subject.next(true);
  }

  stop() {
    this._Subject.next(false);
  }

}
  • Related