简体   繁体   中英

How to use same functionalities of function present in one component to another based on click to use same class binding in both components in angular

I'm using class binding to add and remove classes based on click of sidebar button to minimize and maximize the sidebar. I need same functionality to add and remove class in footer component also to maximize and minimize width of the footer based on click made in sidebar component.

sidebar.component.html

<nav class="sidebar-container" [ngClass]="minimize ? 'minimize' : ''">
    <ul>
        <li class="sidebar-minimize">
            <a (click)="clickEvent()">Minmax</a>
        </li>
    </ul>
</nav>

sidebar.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
  minimize: boolean = false;
ngOnInit(): void {
  }
  clickEvent() {
    this.minimize = !this.minimize;
  }
}

But i need same actions to be performed in footer component to add another CSS class through class binding followed by same clickEvent() method because in my situation sidebar component and footer components are interdependent on this clickEvent() function

For eg,

<footer (click)="clickEvent()" [ngClass]="minimize ? 'minimize':''">
<p>footer works</p>
</footer>

Is it possible to use same clickEvent() function in footer component for class binding

So in this case you can use a service. For example in your service you have a property like below:

@Injectable({
  providedIn: 'root'
})
export class TestService {

 private minimize: boolean;
 public minimizeSubject: Subject<void>;

 constructor() {
  this.minimizeSubject = new Subject<void>();
  this.minimize = false;
 }

set setMinimize(minimize: boolean) {
 this.minimize = minimize;
 this.minimizeSubject.next();
}

Sidebar component should look like below:

export class SidebarComponent{

 public minimize: boolean;

 constructor(private testService: TestService) {
   this.minimize = false;
 }

 public onClicked(): void {
   this.minimize = !this.minimize;
   this.testService.setMinimize = this.minimize;
 }

In the end the footer component:

export class FooterComponent implements OnInit, OnDestroy {

private subscription: Subscription;

constructor(private testService: TestService) {

    this.subscription = new Subscription();
}

ngOnInit(): void {
    this.subscription = this.testService.minimizeSubject.subscribe(minimize => {
        this.minimize = minimize;
    });
}

ngOnDestroy(): void {
    this.subscription.unsubscribe();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM