Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass an *ngIf value from one component to another?

I have a common component called PreloaderComponent and I have included it in another component. I need to know how to pass a variable from the parent component to the PreloaderComponent in order to work with an *ngIf statement in the template.

Here is my code:

<div id="preloader" *ngIf="loader">
    <div id="status">
        <div class="spinner"></div>
    </div>
</div>
export class PreloaderComponent implements OnInit {
  constructor() {}

  loader:any;

  ngOnInit() {}

  startLoader(){
    this.loader = true;
    //console.log("start loader="+this.loader);
  }
}

export class NativeExecutiveSummaryComponent implements OnInit {
  ngOnInit() {
    this.preloader.startLoader();
  }
}
like image 803
Sandeep Nambiar Avatar asked Dec 24 '22 04:12

Sandeep Nambiar


2 Answers

You can use ViewChild component method to call method from one component to another component. Write this code in your NativeExecutiveSummaryComponent class. See below code:

// declaration
@BaseImport.ViewChild(PreloaderComponent)
private preloaderComponent: PreloaderComponent;

// use
this.preloaderComponent.startLoader();
like image 129
Sandipsinh Parmar Avatar answered Mar 23 '23 19:03

Sandipsinh Parmar


Create a common service which has loaderSource as a BehaviourSubject and inject the service into the constructor of your component and subscribe to the loader Observable.

loader.service.ts

import { BehaviorSubject } from 'rxjs';

@Injectable()
export class LoaderService {

  private _loaderSource:any = new BehaviourSubject<any>({});
  public loader = this._loaderSource.asObservable();

  //set the loader value
  setLoader(loader){
    this._loaderSource.next(loader);
  }
}

preloader.component.ts

import { LoaderService } from '../services/loader.service.ts'

export class PreloaderComponent implements OnInit {

  constructor(private _loaderService: LoaderService) {}

  public loader:any;

  ngOnInit() {
    this._loaderService.loader.subscribe(load => { this.loader = load });
  }
}

parent.component.ts

import { LoaderService } from '../services/loader.service.ts'

export class ParentComponent implements OnInit {

  constructor(private _loaderService: LoaderService) {}

  ngOnInit() {
    this._loaderService.setLoader(true); // this will set the loader value
  }
}

Your loader var will now contain the value true and will work with your *ngIf

like image 26
blueprintchris Avatar answered Mar 23 '23 21:03

blueprintchris