Как вызвать динамическую функцию между компонентами в Angular - PullRequest
0 голосов
/ 02 октября 2019

Я новичок в angular, и я планирую создать динамическую функцию в моем приложении. Мне нужна динамическая функция (например, вызывается родительский компонент, функция buttonclick на дочернем компоненте будет делать console.log, тогда как при вызове компонента parent2 функция buttonclick будет создавать диалоговое окно с предупреждением). Можно ли вызвать динамическую функцию с различными реализациями для каждого компонента? Как я это сделаю?

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

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

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() {  

  }

}

Ответы [ 2 ]

2 голосов
/ 02 октября 2019

Функция, совместно используемая в angular с использованием сервиса

В angular вы можете создавать сервис и делиться этим сервисом как провайдер во всех функциях. Методы / функции в службе могут быть вызваны из любого компонента, включая дочерний или не дочерний

0 голосов
/ 02 октября 2019

Предположим, я создал пользовательский сервис фильтрации, который можно использовать из компонентов.

filter.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

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

Затем в app.module.ts добавьте import { CustomFilterPipe } from '../filter.pipe'

и назовите его из ваших компонентов, например book-location-name.component.ts файл.

Надеюсь, он вам поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...