Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Access a variable from component to out side of a class( No parent, child relationship)

Tags:

angular

I'm trying to access a variable from a component to outside of a class and there is no relationship(parent/child) to that component. I did some R&D kind of thing but couldn't find the way to do it. If any one have idea please help me.

For example component is like: BankAccountComponent.ts

@Component({
  selector: 'app-bank-account',
  templateUrl: './app-bank.component.html',
  styleUrls: ['./app-bank.component.scss']
export class BankAccountComponent {
  accountFlag: false;
  changeFlag(){
    this.accountFlag = true;
  }
}

out side class like: CustomValidator.ts

export class CustomValidators extends Validators { 
static bankAccValidator(control: AbstractControl): { [key: string]: boolean } | null {
//Here I need to use that component variable i.e accountFlag
return null;
}
like image 446
Roy Avatar asked Nov 02 '25 07:11

Roy


1 Answers

Services are designed for same, (Dependency Injection)

@Injectable()
export class SomeService {
//define a variable
someVariable = "xyz";
}

Provide this service in parent module or root module of the components (app.module.ts)

inject the service in components

one.component.ts
constructor(private someService: SomeService) {

}
// update the variable here
this.someService.someVariable = "Value Changed"

two.component.ts
constructor(private someService: SomeService) {}
// updated variable can be accessed here
console.log(this.someService.someVariable);
like image 137
Akshay Rajput Avatar answered Nov 03 '25 22:11

Akshay Rajput



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!