将动态变量从方法设置为Oninit

时间:2019-01-23 05:26:54

标签: typescript angular6

使用方法通过事件处理变量,并希望在组件初始化时进行设置

options = [ //array that holds dropdown's options
{ name: "All Countries", value: '/allcountries' },
{ name: "India", value: '/india' }
]

i=0; //initializing variable 'i'
onCountrySelect($event) { //method that gets the dropdown value's array position 
this.i=$event.target.options.selectedIndex; //getting the event in 'i'
}

ngOnInit(){
this.selectedOption = this.options[this.i].name; //i want to set that 
variable 'i' here

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用sessionStorage。您可以这样:

options = [ //array that holds dropdown's options
    { name: "All Countries", value: '/allcountries' },
    { name: "India", value: '/india' }
]

i: number = 0;

onCountrySelect($event) { 
    this.i=$event.target.options.selectedIndex;
    sessionStorage.setItem('selectedCountry', JSON.stringify(this.i));
}

ngOnInit(){
    const temp = sessionStorage.getItem('selectedCountry');

    if(temp) {
        this.i = JSON.parse(temp);
    } 

    this.selectedOption = this.options[this.i].name;
}

或者,您可以使用localStorage代替sessionStorage。区别在于,sessionStorage将在您关闭当前浏览器选项卡后立即删除。而localStorage会一直存在,直到您清理cookie'n为止。

编辑:

选项2

构建包含您的变量的服务。

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

@Injectable()
export class SimpleService {
   private selectedCountry: number = 0;

   constructor() { }

   setSelectedCountry(value: number): void {
       this.selectedCountry = value;
   }

   getSelectedCountry(): number {
       return this.selectedCountry;
   }
}

您必须将服务导入模块并提供。

import { ComponentA } from './component-a.ts';
import { SimpleService } from './simple.service.ts';

@NgModule({
  declarations: [
    ComponentA
  ],
  imports: [
    ComponentA
  ],
  providers: [
      SimpleService
  ]

})
export class XYZModule { }

然后您的组件设置值并获取它。

ComponentA

import { SimpleService } from './simple.service.ts';

constructor(private simpleService: SimpleService) { }

onCountrySelect($event) { 
    this.i=$event.target.options.selectedIndex;
    this.simpleService.setSelectedCountry(this.i);
}

ngOnInit(){
    this.i = this.simpleService.getSelectedCountry();        
    this.selectedOption = this.options[this.i].name;
}

无论您喜欢哪种选择,在编写代码时都必须有点冗长。但是,没有班轮。