3

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 class="assign-box"> <table class="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 class="fa fa-plus" aria-hidden="true"></i> </button> <div class="d-flex flex-row justify-content-end"> <button type="button" class="btn btn-primary" 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 } } 
7
  • no they are not related Commented Dec 12, 2021 at 8:58
  • both are different component but connected them through dialog Commented Dec 12, 2021 at 9:08
  • When you click on Assign All button, then openDialog() method is called. and then what do you think to happen ? Commented Dec 12, 2021 at 9:36
  • the dialog should open along with assignToAll() method in employee component.ts should render can you helpme out in solving this. Commented Dec 12, 2021 at 9:53
  • its working for two buttons but I need only button to work to for assignAll(). Commented Dec 12, 2021 at 12:11

5 Answers 5

1

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 } } 
Sign up to request clarification or add additional context in comments.

Comments

0

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. :)

Comments

0

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

Comments

0

Best Option is to use Event Emitter call an Event Emitter in the AssignCourseComponent, And Call the assignToAll Function inside the Subscription of Event Emitter in EmployeeComponent

1 Comment

@Output() ExampleEmitter: EventEmitter<any> = new EventEmitter(); Example_Emitter(pValue) { this.ExampleEmitter.emit(pValue); } Subscribe_Example_Emitter() { return this.ExampleEmitter; } AssignCourseComponent.ts //call the Event Emitter: this.Example_Emitter('true') EmployeeComponent //Subscribe to hit this.Subscribe_Example_Emitter().subscribe(avalue => { if(value==true){ this.assignToAll() } });
0

my-component-1.component.html

<app-my-component-2 #myComponent></app-my-component-2>

my-component-1.component.ts

import { Component, ViewChild } from '@angular/core'; import { MyComponent2Component } from '../my-component-2/my-component-2.component'; @Component({ selector: 'app-my-component-1', templateUrl: './my-component-1.component.html', styleUrls: ['./my-component-1.component.css'] }) export class MyComponent1Component { @ViewChild('myComponent') myComponent2: MyComponent2Component; constructor() { this.myComponent2.print(); } }

my-component-2.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-my-component-2', templateUrl: './my-component-2.component.html', styleUrls: ['./my-component-2.component.css'] }) export class MyComponent2Component { public print(): void { console.log('Hello World!'); } }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.