I wanted to have a 2-way binding variable declared in the body tag ie the name of the variable wanted to be declared is "menuToggle" (please refer the index.html in the plunker).
I wanted to have some button in the App.component which would get clicked and toggle the class in the variable declared in the body tag. This app.component is loaded/bootstrapped from AppModule.
The Issue here i am facing is the "body" tag which is outside the "my-app" selector where the application is loaded. How do i assign some values outside the application boundary in this case "body" tag.
<body [ngClass] = "{menuToggle: nav-md}">
<my-app>Loading...</my-app>
</body>
Please find the plunker where I have tried implementing this, but I am not able to assign a value to the variable in the body tag.
any ideas how to achieve this or any workarounds available?
It isn't possible, because <body>
is outside of initialized app, as it was already mentioned.
The classes should be added to <body>
manually. setElementClass
method from Renderer
abstraction can be used instead of jQuery or addClass
/ removeClass
methods, like that :
menuToggle$ = new BehaviorSubject(false);
constructor(private renderer: Renderer) {
this.menuToggle$.subscribe((visible) => {
this.renderer.setElementClass(document.body, "nav-md", !visible);
this.renderer.setElementClass(document.body, "nav-sm", visible);
});
...
}
MenuToggle() {
this.isMenuVisible = !this.isMenuVisible;
this.menuToggle$.next(this.isMenuVisible);
}
RxJS BehaviorSubject
is favoured here over EventEmitter
because the former accepts initial value ( false
), so initialization can be skipped in constructor.
If the toggle is used anywhere else, it has to be moved to shared service.
The more appropriate and probably simpler way is to design CSS rules to not rely on changeable body
classes. The application itself can be moved from my-app
to body
selector to cover other layout issues.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.