How can I change the css style in another component by clicking the button?

4.3k Views Asked by At

I have developed a component test1 which contains a button and a <p>Hello World</p>. When I click on the button the background color of the paragraph changes. But now I want to change the background color in app.component when I click on the button. I tried to solve the problem with @Input, but unfortunately it does not work yet. Can you please help me? My Stackblitz

My code:

// test1.component

// HTML
<button type="button" (click)="testHandler()">Change Color</button>
<p [class.toggled]="classToggled">Hello World</p>

// CSS
.toggled {
background-color: blue !important;
}

// TS
public classToggled = false;
testHandler() {
this.classToggled = true;
}
// app.component

// HTML
<div class="wrapper" [class.test1]="classToggled">
  <router-outlet></router-outlet>
</div>

// CSS
.test1 {
  background-color: red !important;
}

// TS
 @Input()  public classToggled = false;
2

There are 2 best solutions below

0
On

Hello you can use ngClass and pass a parameter. NgClass Angular

1
On

There are multiple ways to do it.

For unrelated components, you could use a singleton service to share a styling object between the components and bind it using [ngStyle].

styling.service.ts

@Injectable({ providedIn: 'root' })
export class StylingService {
  sharedStyleSource = new ReplaySubject<any>(1);
  public sharedStyle$ = this.sharedStyleSource.asObservable();

  constructor() { }

  newStyle(value: any) {
    this.sharedStyleSource.next(value);
  }
}

app.component.ts

import { StylingService } from './styling.service';

@Component({
  ...
})
export class AppComponent  {
  constructor(private styling: StylingService) { }

  onClick() {
    this.styling.newStyle({ 'background-color': 'blue' });
  }
}

app.component.html

<button (mouseup)="onClick()">Change child style</button>

<app-test></app-test>

test.component.ts

import { StylingService } from '../styling.service';

@Component({
  ...
})
export class TestComponent {
  constructor(private styling: StylingService) { }
}

test.component.html

<p [ngStyle]="(styling.sharedStyle$ | async)">
  test works!
</p>

Working example: Stackblitz