Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何将ngClass应用于基于元素的应用程序?_Angular - Fatal编程技术网

Angular 如何将ngClass应用于基于元素的应用程序?

Angular 如何将ngClass应用于基于元素的应用程序?,angular,Angular,我有一个服务,它将打开的块状态存储为: export class BlocksStateService { public openedBlockState = new Map<number, boolean>; setState(id: number, state: boolean) { this.openedBlockState.set(id, state); } getState(id: number): boolean {

我有一个服务,它将打开的块状态存储为:

export class BlocksStateService {
   public openedBlockState = new Map<number, boolean>;

   setState(id: number, state: boolean) {
     this.openedBlockState.set(id, state);
   }
  
   getState(id: number): boolean {
      return this.openedBlockState.get(id);
   }
}
然后在模板中:

<div [class.opened]="isBlockOpened(id)"></div>


我知道在模板中使用函数是不好的做法。如何更恰当地将模型数据应用于ngClass?

ngClass的方法表达式

<div [ngClass]="getSomeClass(id)"></div>

您可以使用ngClass的angular

首先,您可以更改组件isBlockOpened函数

public isBlockOpened(id: number): boolean {
     return this.blocksStateService.getState(id) ? true : false;
}
然后您需要更改component.html文件

<div [ngClass]="{'opened': isBlockOpened(id)}"></div>


您也可以在ngClass中使用函数,但要在ngClass中使用模型数据,模型变量应该存在于组件本身中,并且具有公共可视性。您可以分享一个示例吗?可以使用管道吗?我想到的解决方案将避免使用
BlockStateService
,并将
openedBlockState
映射移动到组件本身,然后在ngClass中使用它,如
[ngClass]={'opened':openBlockState.get(id)}
但我也不认为这是个好主意,因为使用服务是一种好做法。我不能在组件中移动状态,因为组件会重新创建状态,所以我会丢失一个状态。为什么不将状态分配给组件init上的本地字段?我说我尽量避免在templateok中使用functon,还有一个选项是在组件中创建属性,并在函数中设置此属性的值,并将此属性与ngClassI绑定到组件中的“无法移动”状态,因为组件会重新创建,所以我会丢失一个状态。在何处设置状态?openedBlockState.set(id,state)?这将在何处设置状态?请检查我的问题我不想从模板调用函数。
public isBlockOpened(id: number): boolean {
     return this.blocksStateService.getState(id) ? true : false;
}
<div [ngClass]="{'opened': isBlockOpened(id)}"></div>