从一个组件调用一个方法到另一个组件

问题描述 投票:0回答:5

assignToAll
方法位于
EmployeeComponent
中,但需要从
AssignCourseComponent
调用它如何实现

分配课程.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 } });
    
  }
}

当单击分配全部时,它应该呈现

EmployeeComponent
assignToEmployees()
方法

分配课程.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> 

这是

employee.component.ts
AssignToAll
方法的实现

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
  }
}
angular typescript angular-components
5个回答
1
投票

共享数据.service.ts

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

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

  constructor() { }

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

组件1.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 
  }
}

组件2.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 
  }
}

0
投票

你不能那样做。因为组件有其作用域,并且您无法访问它们的方法。你能做的是:

  1. 使用

    ng g s shared-functions
    创建服务。

  2. 在那里定义您的功能。

  3. 在两个组件中实例化它。

  4. 在两个组件中使用它们。 :)


0
投票

通常,为了解决更复杂的问题,建议使用以下设计模式。以下方法为示例。

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

}

0
投票

最好的选择是使用事件发射器 在AssignCourseComponent中调用Event Emitter,并调用assignToAll EmployeeComponent 中事件发射器订阅内的函数


0
投票

我的组件-1.component.html

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

我的组件-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();
  }
}

我的组件-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!');
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.