Angular 2/4:从根组件调用组件的方法

时间:2017-07-19 09:25:01

标签: angular typescript

我有一种方法" changeLanguage"在我的appComponent中更改应用程序语言..我有很多组件,如" folderComponent"," AdminComponent"等等.. 所以当我点击单选按钮语言(En,De)时,我想刷新所有组件的数据,以便用当前语言进行翻译。 的 app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {

   public language = 'fr';

  constructor(
    private authenticationService: AuthenticationService,
    private route: ActivatedRoute,
    private router: Router,
    public translate: TranslateService,
    public folderService: FoldersService) {
    this.name = 'AppComponent';
    this.translate.addLangs(['de', 'fr']);
    this.translate.setDefaultLang('../assets/i18n/fr');
    this.browserLang = this.translate.getBrowserLang();
    this.translate.use(this.browserLang.match(/de|fr/) ? '../assets/i18n/' + this.browserLang : 'fr');
  }


  ngOnInit(): void {
    this.credentials = JSON.parse(localStorage.getItem('credentials'));
  }

  changeLangueCCPD(language: string) {
    this.translate.use('../assets/i18n/' + language);
    ***// Here, how can I call any component for loading data with the current language ? Like call loadData() method of folder;component.ts***
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { FoldersComponent } from './folders/folders.component';
import { AdminComponent } from './admin/admin.component';
@NgModule({
  declarations: [AppComponent, FoldersComponent, AdminComponent],
  imports: [BrowserModule, FormsModule, HttpModule, routing, NgbModule.forRoot()],
  providers: [AuthorizationGuard, FoldersService, AdminService],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<span class="spanLabel"> 
<input class="option-input radio" type="radio" (click)="changeLangueCCPD('fr')" name="language" [(ngModel)]="language" value="fr" />
</span>

<span class="spanLabel"> 
<input class="option-input radio" type="radio" (click)="changeLangueCCPD('de')" name="language" [(ngModel)]="language" value="de" />
</span>

folder.component.ts

@Component({
  selector: 'app-folders',
  templateUrl: './folders.component.html',
  styleUrls: ['./folders.component.css'],
  providers: [AppComponent, {provide: Parent, useExisting: FoldersComponent}]
})
export class FoldersComponent implements OnInit {
  public data: any[];
  public language = 'fr';

  constructor(private activateRoute: ActivatedRoute, private router: Router,private foldersService: FoldersService) { }

  ngOnInit() {
     this.loadData();
  }

  public loadData() {
     this.foldersService.getAllFolders().subscribe(
      (data) => {
        this.data = data;
      });
  }
}

0 个答案:

没有答案