Sveta Antrapovich
Sveta Antrapovich

Reputation: 417

Angular 2 dictionary

In Angular 1 my code looked like this:I have 2 dictionaries and functions

var rus = {"hello" : "привет",
"text":"текст",
"home":"дом"};

var eng = {"hello":"hello",
"text":"text",
"home":"home"};
$scope.selectedLang = rus;

translate();

function translate() {
    $scope.hello = $scope.selectedLang["hello"];
    $scope.text = $scope.selectedLang["text"];
    $scope.home = $scope.selectedLang["home"];
}

$scope.switchLang = function(lang) {
    if(lang == "rus") {
        $scope.selectedLang = rus;
    } else {
        $scope.selectedLang = eng;
    }
    translate();
};

But now I need to make this in angular 2. How can I do this?

Upvotes: 1

Views: 2540

Answers (1)

Bhushan Gadekar
Bhushan Gadekar

Reputation: 13805

I have included only class logic here,hope this helps:

export class AppComponent implements OnInit{ 
    public hello:any;
    public text:any;
    public home:any;
    private rus = {
        "hello" : "привет",
        "text":"текст",
        "home":"дом"
    };
   private eng = {
       "hello":"hello",
       "text":"text",
       "home":"home"
   };
   private selectedLang:any;
   ngOnInit(){
       this.selectedLang = this.rus;
       this.switchLang('rus'); //calling switchLang() method 
   }
   private selectedLang = this.rus;

   translate() {
       this.hello = this.selectedLang["hello"];
       this.text = this.selectedLang["text"];
       this.home = this.selectedLang["home"];
   }  
   switchLang (lang:string){
        if(lang == "rus") {
            this.selectedLang = this.rus;
        } else {
            this.selectedLang = this.eng;
        }
        this.translate();
   }
}

Upvotes: 3

Related Questions