angular-ngif条件内的body标签类名称

时间:2019-08-27 06:47:15

标签: javascript angular

Body标签可以有两个可能的类名darklight,这是检查HTML中哪个类处于活动状态而不在.ts文件中声明变量的最佳方法。

<body class="dark"></body>
       or
<body class="light"></body>

<img *ngIf="If body is having class name 'dark' show this">
<img *ngIf="If body is having class name 'light' show this"> 

我尝试过,但是没有用

<img *ngIf="document.body.className === 'dark'"> 

4 个答案:

答案 0 :(得分:0)

难道不只是在组件中添加变量并检查img和主体中的var是否为* ngIf?

<body [class]="myVar=="dark" ? 'dark' : 'light'">
<img *ngIf="myVar='dark'">

答案 1 :(得分:0)

使用变量设置主题和img

theme = 'dark' ;

<body ng-class="{theme === 'dark' ? 'dark' : 'light'}"></body>
<img *ngIf="theme == 'dark'"> 
<img *ngIf="theme !== 'dark'"> 

答案 2 :(得分:0)

在其他答案中已经提到了许多可能的方法,因为我们需要在不使用ts或js的情况下解决此问题

我们只能使用CSS和HTML来解决它

尽管添加了ngIf来加载不同的图像,但是这里的方法还是可以使用CSS加载不同的图像

<body class="dark">
<img class="image-replacement"  />


</body>

.dark .image-replacement {
  display: block;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: url(http://akamaicovers.oreilly.com/images/9780596517748/cat.gif) no-repeat;
  width: 180px;
  height: 236px;
  padding-left: 180px;
}

.light .image-replacement {
  display: block;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: url(http://ashlandtech.org/wp-content/uploads/2014/09/1.png) no-repeat;
  width: 180px;
  height: 236px;
  padding-left: 180px;
}

请找到工作小提琴链接https://jsfiddle.net/vickykumarui/4po9hu6g/

就您的代码而言,它是正确的 可能无法正常工作的原因之一是因为文档没有注入到您的角度组件中 将文档注入角组件后,它将开始工作

import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(@Inject(DOCUMENT) private document: Document) {}
}

请找到您遵循的方法的工作演示 https://stackblitz.com/edit/angular-qighyt

答案 3 :(得分:0)

<body class="light" #classref>
    <img *ngIf="classref.className === 'dark'" title="dark">
    <img *ngIf="classref.className === 'light'" title="light">
</body>
  

您可以为元素设置参考变量。   classref作为body元素的引用变量,因此我们可以通过* ngIf检查类名。