简体   繁体   中英

how to call a component method from another component in angular 2?

i have two components in my angular 2 app and i have a md-select in one of them that contain two languages. i want to change the whole project direction after i select one of the languages.

here is part of my component1.html:

<md-select class="data_font"  [(ngModel)]="currentLang" #langSelect="ngModel" (ngModelChange)="translate.use(currentLang)">
            <md-option *ngFor="let lang of translate.getLangs()" [value]="lang"><span class="data_font">{{ lang }}</span></md-option>
</md-select>

and this is part of component2.html:

<div #root="$implicit" dir="rtl" >
   ...//some html code here
</div>

and part of component2.ts

currentLang = 'fa';
@ViewChild('root') root;
ngAfterViewInit(): void {
    this.root.dir = 'rtl';
  }
RTL(){
    if(this.currentLang == 'fa'){
      this.root.dir = 'rtl';
    }
    if(this.currentLang == 'en'){
      this.root.dir = 'ltr';
    }
  }

i can change the direction where root and dir is exist but i want to do it from component 1. how can i do it?is there any way to call RTL() in component1?

For your case you can create a service and keep an observable for the language propety in that service... Observable will help you subscribe to the change in the property value at any point of time...and you can change you functions as per you service-propety's current value.... + follow the link to learn more about observables: https://toddmotto.com/rxjs-observables-observers-operators .

Basically, If two of your components need to share a same functionality or data you should convert that functionality into a service as a property or method...for example lets say you have a cart dropdown (component) where user can increase or decrease the final quantity of the products added and the same functionality is given to the user or order confirmation page (another component) since both the components share the similar functionality...a service should be created that could handle any requests coming from any component to handle cart events. Hope the example would help.

If your component 1 call component 2 or the opposite you can use ViewChild as one of the component will be the child. In case your component are at the same level or on two different component you can exchange data using a service injected in both components constructor. One calling the service the other one subscribing to the data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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