简体   繁体   中英

how to access or update variable of other component without using service class in Angular 4

how to access or update other component variable without shared service

i have these two component

NOTE : these components are not Parent/Child

component 1 : src/app/ABC/one/more/step/C1.component.ts

import { Component} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './C1.component.html',    
})

export class C1Component implements OnInit {


  x1:any;

  constructor() 


  ngOnInit() {    
  }

}

component 1 : src/app/XYZ/two/more/step/C2.component.ts

import { Component} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './C2.component.html',    
})

export class C2Component implements OnInit { 


  constructor() 


  ngOnInit() {    
  }

  submit()
  {
    // after submit update the C1.component.ts variable 'x1' here
  }
}

Thanks ahead !

You really should use a shared service for such a task, because you can access and modify it's properties from every component where it is injected. And it ensures angular's change detection is picking up changes properly.


But if you don't want to use it (please consider using it!) you could go for a static property of the component class:

export class C2Component {
  public static shared: string = 'foo';
}

import { C2Component } from '...';
// ...

export class C1Component {
  submit() {
    C2Component.shared = 'bar';
  }
}

But this will likely cause some problems regarding change detection.

Or you could use a global variable which sits on the window object, but this is even worse. So please don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM