簡體   English   中英

如何從不同的組件調用其他組件函數?

[英]How to call other component function from different component?

我有這樣的html結構:

Comp1Comp2所在的父組件:

現在在comp1我有一些元素(如果發生更改),那么我必須在comp2反映值,但是它們之間沒有任何聯系。

Comp1:

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

import { Comp2Component } from 'comp2.component';

@Component({
  selector: 'comp1',
  templateUrl: './comp1.html'
})
export class Comp1Component {

    sortBy(value)
    {
        this.FeedSortBy = value;
        this.SortByLabel = this.SortByLabelList[value];
        Comp2Component.filterActivities();
    }
}

Comp2

import { Component } from '@angular/core';
    @Component({
      selector: 'comp2',
      templateUrl: './comp2.html'
    })
    export class Comp2Component {

     filterActivities()
     {
         //call this function on comp1 sort function call so it will update value of comp2
     }

  }

根據Rahul和Sajit的回答,我嘗試與EventEmitter一起使用,並將我的結構更改為父母孩子:

在我的父組件中,我使用:

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

import { FeedsComponent } from '../feeds/feeds.component';

@Component({
  selector: 'my-desk',
  styleUrls: ['../../assets/css/style.min.css'],
  templateUrl: './my-desk.component.html'
})
export class MyDeskComponent {

    @Output() FeedSortBy = new EventEmitter<string>();
    sortBy(value)
    {
        this.FeedSortBy.emit(value);
    }
}

在子組件中,我使用:

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

import { DataService } from '../data.service';

declare var $: any;

@Component({
  selector: 'feeds',
  styleUrls: ['../../assets/css/style.min.css'],
  templateUrl: './feeds.component.html'
})
export class FeedsComponent {
    constructor(private dataService:DataService)
    {

    }
    @Input() FeedSortBy:number = 2;
}

子組件HTML:

{{FeedSortBy}}

但是它總是輸出2它不會改變,我也可以得到任何觸發器來知道值是否改變,所以我在那里調用函數

cannot做到這一點,有兩種方法可以實現這一目標,

  1. 使用angular service在兩個組件之間傳遞數據

  2. 使用Event Emitters在組件之間傳遞值。

您可以從其他組件中調用另一個組件的方法,但是如果它們具有父子關系或Shared Services或使用ngrx redux pattern諸如Event Emitters類的一些調整就不會更新調用組件的值。

如何調用不同的組件方法就像

組件1

  test(){
    console.log("Test");
  }

組成部分2

  working(){
    let component = new Component1();
    component.test();
  }

現在,要更新組件2中的值,您可能必須使用上述任何一種。

對於事件發射器,請單擊此鏈接

對於共享服務,請點擊此鏈接

對於ngrx,請點擊此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM