Jaime Gómez
Jaime Gómez

Reputation: 49

Change value of variable from component to other (non related components)

Is there a way to change the value of the variable called variable1 in the component 2 from component 1 making click in the function of this component ?

Component 1 ts

@Component({
  selector:    'app-component1',
  templateUrl: './component1.html',
})
export class Component1 implements OnInit {
  changeVariable(){
      
  }
}

component1.html

<div (click)="changeVariable()"></div>

Component 2 ts

@Component({
  selector:    'app-component2',
  templateUrl: './component2.html',
})
export class Component2 implements OnInit {
  variable1: boolean = false
}

Upvotes: 3

Views: 5889

Answers (1)

skouch2022
skouch2022

Reputation: 1161

You have 2 options:

  1. Pass the component2 context/reference into component1.
  2. 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

Upvotes: 1

Related Questions