S
S
sdgroup142018-02-28 14:46:30
JavaScript
sdgroup14, 2018-02-28 14:46:30

How to implement a Service that is only responsible for a set of boolean values ​​in Angular 2-5?

There are a lot of modals... there are a lot of buttons.... I'm making a connection through a service... And I don't have enough skills to make 1 service for everything for each modal button. Not for each... the example code below is the same for each modal. There are 5 at this stage.


//Service
@Output() change: EventEmitter = new EventEmitter();
categoryModalisOpen = false;
toggleCreateCategoryModal() {
this.categoryModalisOpen = !this.categoryModalisOpen;
this.change.emit(this.categoryModalisOpen);
}
//BtnComponent
constructor(
private CreateCategoryModalService: CreateCategoryModalService
) { }
openCreteCatModal() {
this.CreateCategoryModalService.toggleCreateCategoryModal();
}
//ModalComponent
createCatIsOpen = false;
ngOnInit() {
this.CreateCategoryModalService.change.subscribe(isOpen => {
this.creatCatIsOpen = isOpen;
});
}
constructor(
private CreateCategoryModalService: CreateCategoryModalService
) { }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kalibrov, 2018-02-28
@sdgroup14

Something like this:

//Service

@Output() change: EventEmitter[];

categoryModalisOpen[] = [];

toggleCreateCategoryModal(key) {
this.categoryModalisOpen[key] = !this.categoryModalisOpen[key];
this.change[key].emit(this.categoryModalisOpen[key]);
}

//BtnComponent

@ViewChild('modalComponentInstance') // # ссылка на компонент нужного модального окна
modalComponentInstance;

constructor(
private CreateCategoryModalService: CreateCategoryModalService
) { }

openCreteCatModal() {
let key = this.modalComponentInstance.key; // Нужно подключить инстанс окна которое должно открываться по текущей кнопке 
this.CreateCategoryModalService.toggleCreateCategoryModal(key);
}

//ModalComponent

creatCatIsOpen = false;
key: number;

ngOnInit() {
this.key = this.CreateCategoryModalService.categoryModalisOpen.lenght + 1;
this.CreateCategoryModalService.change[this.key].subscribe(isOpen => {
this.creatCatIsOpen = isOpen;
});
}

constructor(
private CreateCategoryModalService: CreateCategoryModalService
) { }

I didn’t check the code, I just ran it in my head, there are probably some errors, but the main thing is that you understand the essence of the idea.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question