Hemang
Hemang

Reputation: 27050

How to call a component condition at the time of rendering

my-component is a reusable component, so while I try to render it in different components I want to test a condition, if it satisfies then only it should render into the DOM.

<app1>
<my-component *ngIf="aConditionCheckFromMyComponent"></my-component>
<app1>

<app2>
<my-component *ngIf="aConditionCheckFromMyComponent"></my-component>
<app2>

My idea is to create a service and then create another function which return the same condition

import my-component
class Utility {

constructor(private mc: my-component) {
}

get anotherConditionFunction(): boolean {
 return mc.aConditionCheckFromMyComponent();
}

now I can use: utilityObj.anotherConditionFunction();

... but I don't find it proper. Do you have any other ways? How to do this properly?

Upvotes: 1

Views: 882

Answers (1)

Moslem_mh
Moslem_mh

Reputation: 189

i had the same problem and i solved it by creating an Injectable class,placing it in app folder and imported it in all components that nead to use global conditions

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

@Injectable()
export class Globals {

    showSomeComponent = false;
    public constructor() {
        this.showSomeComponent = true;
    }
    public setShowSomeComponent (flag) {
        this.showSomeComponent = flag;
    }
}

You can change this flag anywhere in the app and instantly all the components that use it will see this change.

usage example:

import {Globals} from '../../globals';
@Component({
    selector: 'app-component-1',
    templateUrl: './component-1.component.html',
    styleUrls: ['./component-1.component.sass']
})
export class RavanDataGridComponent implements OnInit {
constructor(private globals: Globals) {
    
}

html:

<app-module-menu *ngIf="this.globals.showSomeComponent">
        </app-module-menu>

Upvotes: 1

Related Questions