You have 2 options:
- Pass the component2 context/reference into component1.
- Use service to store the variable1, and it can be then share between component1 and component2.
Option 1
If non-related means sibling components which is used side by side in a parent component like below:
<div class="parent-div">
<app-component-1> </app-component-1>
<app-component-2> </app-component-2>
</div>
Then you can pass the context of the component-2 into component-1.
component1.ts
import { Component, Input } from '@angular/core';
import { Component2Component } from '../component-2/component-2.component';
@Component({
selector: 'app-component-1',
templateUrl: './component-1.component.html',
styleUrls: ['./component-1.component.css']
})
export class Component1Component {
// This will allow you to pass in component2 context/reference.
@Input()
public component2Context!: Component2Component;
constructor() { }
public changeVariable() {
// After passing component2 context, you can call all its public functions/properties.
this.component2Context.variable1 = true;
}
}
component1.html
<button (click)="changeVariable()">Change Variable 1</button>
component2.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-component-2',
templateUrl: './component-2.component.html',
styleUrls: ['./component-2.component.css'],
})
export class Component2Component {
public variable1 = false;
constructor() {}
}
component2.html
<div>Component2.variable1 = {{ variable1 }}</div>
Then in the Parent, you need to pass the reference from component2 into the component1 like below:
parent.html
<div class="parent-div">
<app-component-1 [component2Context]="comp2Context"></app-component-1>
<app-component-2 #comp2Context></app-component-2>
</div>
Option 2
You can use a service to store the variable1. Then any components can have access to it. Component1 can update its value, and component2 can see the updated value.
Here is the demo I created: https://stackblitz.com/edit/angular-ivy-qj7mer