0
votes

I'm trying to change button's style by clicking other button in a different component.

Right now, I have a main html page and there's an angular component loaded on page using angular selector <component1></component1>

Here's main html file containing the component:

                  <button id="button01" 
                  tappable>
                     <ion-icon name="square" [ngClass]="Btn1"></ion-icon>
                   </button>                                          

                  <button id="button02" 
                  tappable>
                     <ion-icon name="square" [ngClass]="Btn2"></ion-icon>
                   </button>

and here's my component HTML file. It has a button that is trying to change that Btn1 and Btn2 style to button-active3 class.

<button id="componentbutton" tappable (click)="Btn1='button-active3'; 
  Btn2='button-inactive';">Change Color!</button>

button-active3 and button-inactive are styles classes of button in my SCSS file.

I found this configuration doesn't trigger component's button to change styles of buttons in the main html file.

How can I make this work?

If I put that component's button inside the main HTML file, it will work fine.. but I think it doesn't work because now the button is in a component and the component can't access to ngClass of main HTML file.

Please help. If there's a way to work around it, let me know.

Thanks in advance.

1
I would create a service and use that to communicate between your main page and the component. - David Lee
Hi David, yes. I have tried.. but I wonder how to execute Btn1='button-active3' as a function in service. It didn't work. Is it possible for you to show me an example? thanks a lot! - jamesharvey
so basically you want a nested(child) components click event to change parents html class by clicking a button from child component? - Mahesh Jadhav

1 Answers

0
votes

For communication between child and parent you can use angular's EventEmitter property which triggers an event on some action using the @Output decorator and the parent binds to that event property and reacts to those events:

Child component html:

<button id="componentbutton" tappable (click)="someFunction()">Change Color!</button> // you can pass paramters inside the function if you want to trigger an event by passing some values to parent

Child ts:

@Output() changeClass: EventEmitter<any> = new EventEmitter<any>(); //import output from @angular/core

someFunction() {
  this.changeClass.emit();
}

Parent html:

<componentName (changeClass)="anotherFn($event)"></componentName>

Parent ts:

anotherFn(){
  this.Btn1 ='button-active3';
  this.Btn2 ='button-inactive';
}

then you can easily bind Btn1 and Btn2 anywhere you want and you will get the classes applied

<ion-icon name="square" [ngClass]="Btn1"></ion-icon>
<ion-icon name="square" [ngClass]="Btn2"></ion-icon>