简体   繁体   English

如何在 Angular 中的组件之间调用动态 function

[英]How to call a dynamic function between components in Angular

I'm new to angular and I'm planning on making a dynamic function on my app.我是 angular 的新手,我计划在我的应用程序上制作动态 function。 I wanted a dynamic function (ex. Parent component is called, the buttonclick function on the child component will do a console.log, while when parent2 component is called, the buttonclick function will do an alert dialog).我想要一个动态的 function (例如,调用父组件,子组件上的按钮单击 function 将执行 console.log,而当调用 parent2 组件时,按钮单击 ZC1C425268E68385D1AB4Z5074C 将执行警报对话框)7A94F Is it possible to call a dynamic function with different implementations for each component?是否可以为每个组件调用具有不同实现的动态 function? How will I do it?我将如何做?

child.component.ts child.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-child',
  template : '<button click()="dynamicFunction()">Click!</button>',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  constructor() { }

  dynamicFunction(){
     //do nothing
  }  

  ngOnInit() {  

  }

}

parent.component.ts父组件.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  template : '<app-child></app-child>',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  constructor() { }

  dynamicFunction(){
      console.log('parent 1 clicked');
  }  

  ngOnInit() {  

  }

}

parent2.component.ts parent2.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent2',
  template : '<app-child></app-child>',
  styleUrls: ['./parentTwo.component.css']
})
export class ParentTwoComponent implements OnInit {

  constructor() { }

  dynamicFunction(){
      alert('parent 2 was called');
  }  

  ngOnInit() {  

  }

}

Function shared in angular using service Function 共享在 angular 使用服务

In angular you can create service and share that service as provider in all the function.在 angular 中,您可以在所有 function 中创建服务并作为提供者共享该服务。 The methods/function in the service can be called from any component including child or non child可以从任何组件调用服务中的方法/函数,包括子组件或非子组件

Suppose I have created a custom filter service that can be use from components.假设我创建了一个可以从组件中使用的自定义过滤器服务。

filter.pipe.ts过滤器.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({
      name: 'filter'
    })
    export class CustomFilterPipe implements PipeTransform {
      transform(items: any, filter: any, defaultFilter: boolean): any {
        debugger;
        if (!filter) {
          return items;
        }

        if (!Array.isArray(items)) {
          return items;
        }

        if (filter && Array.isArray(items)) {
          let filterKeys = Object.keys(filter);

          if (defaultFilter) {
            return items.filter(item =>
              filterKeys.reduce((x, keyName) =>
                (x && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] == "", true));
          }
          else {
            return items.filter(item => {
              return filterKeys.some((keyName) => {
                return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] == "";
              });
            });
          }
        }
      }
    }

book-location-name.component.html书籍位置名称.component.html

<table class="table table-bordered bordered table-striped table-condensed table-text table-scroll table-hover">
          <thead class="thead">
            <tr>
              <th style="width:5%;">Sl</th>
              <th style="width:30%;">Location Name &nbsp;</th>
              <th style="width:25%;">Location Code &nbsp;</th>
              <th style="width:15%;">Is Active &nbsp;</th>
              <th style="width:25%;">Action&nbsp;</th>
              <th *ngIf="LocationNameList.length>5" style=" width: 2%;"></th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let dataModel of LocationNameList| filter : {LocationName: searchText, LocationCode:searchText} | paginate: config; let i=index">
              <td style="display:none">{{dataModel.BlnId}}</td>
              <td style="width:5%;"> {{i+1}}</td>
              <td style="width:30%;"> {{dataModel.LocationName}}</td>
              <td style="width:25%;"> {{dataModel.LocationCode}}</td>
              <td style="width:15%;">
                <span class="badge" [ngClass]="{'badge-success':dataModel.IsActive, 'badge-secondary':!dataModel.IsActive}">{{dataModel.IsActive==true?'Active':'Inactive'}}</span>
              </td>
              <td>
                <i (click)="editData(dataModel)" class="cui-note icons font-2xl mt-4" style="cursor:pointer;"></i>
                &nbsp;&nbsp;&nbsp;
                <i (click)="showConfirmationModal(2,dataModel.BlnId)" class="cui-trash icons font-2xl mt-4" style="cursor:pointer;"></i>
              </td>
            </tr>
          </tbody>
        </table>

Then in app.module.ts add import { CustomFilterPipe } from '../filter.pipe'然后在 app.module.ts 添加import { CustomFilterPipe } from '../filter.pipe'

And call it from your components like book-location-name.component.ts file.并从您的组件中调用它,例如book-location-name.component.ts文件。

Hope it's help you.希望对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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