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();
}
}
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();
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
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