Angular 如何在渲染时调用组件条件

Angular 如何在渲染时调用组件条件,angular,dom,angular-ng-if,Angular,Dom,Angular Ng If,my component是一个可重用的组件,所以当我尝试在不同的组件中呈现它时,我想测试一个条件,如果它满足,那么它应该只呈现到DOM中 <app1> <my-component *ngIf="aConditionCheckFromMyComponent"></my-component> <app1> <app2> <my-component *ngIf="aConditionCheckFromMy

my component
是一个可重用的组件,所以当我尝试在不同的组件中呈现它时,我想测试一个条件,如果它满足,那么它应该只呈现到DOM中

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

<app2>
<my-component *ngIf="aConditionCheckFromMyComponent"></my-component>
<app2>
现在我可以使用:
utilityObj.anotherConditionFunction()


。。。但我觉得这不合适。你还有别的办法吗?如何正确地做到这一点?

我也遇到了同样的问题,我通过创建一个可注入类来解决它,将其放置在app文件夹中,并将其导入所有需要使用全局条件的组件中

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

@Injectable()
export class Globals {

    showSomeComponent = false;
    public constructor() {
        this.showSomeComponent = true;
    }
    public setShowSomeComponent (flag) {
        this.showSomeComponent = flag;
    }
}
您可以在应用程序中的任何位置更改此标志,使用此标志的所有组件都会立即看到此更改

用法示例:

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:



在服务中定义条件并从多个组件调用它这是唯一的方法吗?没有其他易于维护的解决方案@T.SunilRaoComponents并不意味着共享它们的控制器内容(),您应该在一个服务中定义您的条件,该服务可以在您希望访问它的任何地方注入。这取决于您的用例。请详细说明您的用例以进行优化solution@T.SunilRao,我有一个页脚栏,它应该根据条件显示,现在页脚栏在每个位置(在每个组件中),但只有满足条件时才应该显示。
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) {
    
}
<app-module-menu *ngIf="this.globals.showSomeComponent">
        </app-module-menu>