0

Is it possible to completely separate the presentation logic (e.g. Toggling UI, Show / hide modal dialog etc.) from component level ? so the component will ONLY handle the data, thus the component won't have UI related functions like hideModal() or showModal().

Matt Downey
  • 363
  • 6
  • 18
  • Have a look at this [**answer**](http://stackoverflow.com/questions/42735858/how-to-show-hide-bootstrap-modal-from-a-component/42736058#42736058) – Aravind Apr 02 '17 at 14:16

1 Answers1

0

You can just move every logic to a service and then bind the view to the service.

@Injectable()
export ModalService {
  show:bool = false;
  hideModal() { this.show = false; }
  showModal() { this.show = true; }
}

@Component({
   template: '<div>{{modalService.show}}</div><button (click)="modalService.show ? modalService.hide() : modalService.show()">toggle</button>
   providers: [ModalService],
})
class ModalComponent {
  constructor(private:modalService:ModalService){}
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Beside showing or hiding the modal, I also need to pass data when I click it to show the modal. I've been using BehaviorSubject inside the ViewService, and having the component to subscribe to the Subject to listen for incoming data. However, this approach bloated my component to have to subscribe and also unsubscribe from the subject, it works. But I was still thinking if there's any other 'best' approach for this. – Matt Downey Apr 02 '17 at 14:59
  • 1
    Why would you need to subscribe and unsubscribe in the component? Usually using the async pipe (`| async`) in view bindings is enough. – Günter Zöchbauer Apr 02 '17 at 15:15