我有一个不同选项的下拉列表。我想将选定的选项保留在下拉列表的顶部,直到用户更改它。现在,如果我选择任何选项,然后我退出组件然后回来,下拉菜单重置第一个值....
HTML
<select class="form-control-mb-12"
(change)="intSelection($event.target.value)" >
<option value="1/4">1/4</option>
<option value="1/8">1/8</option>
<option value="1/16">1/16</option>
<option value="1/32">1/32</option>
</select>
组件
import { Component, OnInit } from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import { ModuladorService } from 'app/Services/modulador.service'
@Component({
selector: 'app-resumen',
templateUrl: './resumen.component.html',
styleUrls: ['./resumen.component.scss'],
providers: [ModuladorService]
})
export class ResumenComponent implements OnInit {
intSelected : string = "" ;
constructor(private _moduladorService:ModuladorService) {
this.intSelected = this._moduladorService.obtenerParametros();
}
ngOnInit() {
}
intSelection(value){
switch(value) {
case "1/4":
this.intSelected = value;
break;
case "1/8":
this.intSelected = value;
break;
case "1/16":
this.intSelected = value;
break;
case "1/32":
this.intSelected = value;
break;
}
this._moduladorService.actualizarParametros(this.intSelected);
}
服务
import { Injectable } from '@angular/core';
import { InitParam } from 'app/layout/modulador/resumen/init-param'
@Injectable()
export class ModuladorService extends InitParam {
constructor() {
super();
this.load();
}
obtenerParametros(){
var intSelected = JSON.parse(localStorage.getItem('intSelected'));
return intSelected;
}
actualizarParametros(newParam : any){
var intSelected = JSON.parse(localStorage.getItem('intSelected'));
intSelected = newParam;
localStorage.setItem('intSelected', JSON.stringify(intSelected));
}
}
iNIT FOR SERVICE
export class InitParam {
load(){
if(localStorage.getItem('intSelected')=== null ){
console.log('No se encontraron parametros...');
var intSelected = '1/4'
localStorage.setItem('intSelected', JSON.stringify(intSelected));
}else{
console.log('Cargando parametros...');
}
}
}
答案 0 :(得分:1)
您可以将选定的内容保留在@Injectable
服务中,如果不是这样,则可以使用单个服务器。
或者从/向父组件输入/输出。
答案 1 :(得分:0)
您需要服务中的存储数据。服务可注入模块。 如果您需要在所有应用程序中保存信息 - 请使用app.module.ts
中的提供程序中的服务