Method 1 - Parent-child relationship
You can hide or show the div in the child component with a hideDiv property, and make that property available for data binding with the @Input decorator. The property can toggle the visibility style directly or apply a class to the div:
@Component({
selector: 'child-component',
template: `
<div></div>
<div [class.hiddenClass]="hideDiv"></div>
<div [style.visibility]="hideDiv ? 'hidden' : 'visible'"></div>
<div></div>
`,
styles: [`.hiddenClass { visibility: hidden; }`]
})
export class ChildComponent {
@Input() hideDiv = false;
}
You would then modify it with data binding when clicking on the button in the parent component:
@Component({
selector: 'parent-component',
template: `
<button (click)="hideChildDiv = !hideChildDiv">Toggle div visibility</button>
<child-component [hideDiv]="hideChildDiv" ></child-component>
`
})
export class ParentComponent {
hideChildDiv = false;
}
You can test the code in this stackblitz.
Method 2 - Communication between two components with a service
You can use a service to allow two separate components to communicate with each other or to share some information. See this stackblitz for a demo.
Service:
import { Injectable } from "@angular/core"
@Injectable()
export class VisibilityService {
hideDiv = false;
}
Parent component:
@Component({
selector: 'app-root',
template: `
<child1></child1>
<child2></child2>
`
})
export class AppComponent {
}
Child1 component:
import { VisibilityService } from "./visibility.service";
@Component({
selector: 'child1',
template: `
<button (click)="hideDiv = !hideDiv">Toggle div visibility</button>
`
})
export class Child1Component {
public get hideDiv(): boolean {
return this.visibilityService.hideDiv;
}
public set hideDiv(value: boolean) {
this.visibilityService.hideDiv = value;
}
constructor(private visibilityService: VisibilityService) { }
}
Child2 component:
import { VisibilityService } from "./visibility.service";
@Component({
selector: 'child2',
template: `
<div class="div1"></div>
<div class="div1" [class.hiddenClass]="hideDiv"></div>
<div class="div1"></div>
<div class="div1" [style.visibility]="hideDiv ? 'hidden' : 'visible'"></div>
<div class="div1"></div>
`
})
export class Child2Component {
public get hideDiv(): boolean {
return this.visibilityService.hideDiv;
}
constructor(private visibilityService: VisibilityService) { }
}
Module:
...
import { AppComponent } from './app.component';
import { Child1Component } from './child1.component';
import { Child2Component } from './child2.component';
import { VisibilityService } from "./visibility.service";
@NgModule({
declarations: [
AppComponent,
Child1Component,
Child2Component
],
providers: [
VisibilityService
],
...
})
export class AppModule { }