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;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With