javascript - 为什么 ngStyle 不起作用

标签 javascript angular typescript

我在指令中将属性颜色添加到 ngStyle 属性。但是 ngStyle 没有对元素应用任何样式。编译器根本没有显示任何错误,控制台也没有。我尝试了 ngStyle 的不同语法,但它仍然无法正常工作。

我还在下面添加了 app.modules 代码。加载模块有没有问题。

  import { Directive, ElementRef, OnInit, Renderer2, HostListener, Input } from '@angular/core';
            
            // custom directive which changes background color for odd and even values of index
            @Directive({
              selector: '[appChangecolor]'
            })
            export class ChangecolorDirective implements OnInit {
              @Input() index: any;
                       color: string;
            
              constructor(private elementRef: ElementRef, private render: Renderer2) { }
              // listnes to mouseenter event of the element on which custom directive is applied and calls the function
              @HostListener('mouseenter') bgColor() {
            
                if (this.index % 2 === 0) {
                  // style set through Renderer2 and not by directly accessing DOM element.
                  this.color = 'green';
                } else {
                  this.color = 'red';
                }
                  console.log(this.color);
              }
              // listens to the mouseleave event on the element on which directive is applied
              @HostListener('mouseleave') bgColorRm() {
                this.color = 'black';
                console.log(this.color);
              }
            
              ngOnInit() {
                this.index += 1;
              }
            }



       
 import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { NgStyle } from '@angular/common';
    import {CommonModule} from '@angular/common';
    import { AppComponent } from './app.component';
    // custom directive imported from the respective file
    import { ChangecolorDirective } from './changecolor.directive';
    
    @NgModule({
      declarations: [
        AppComponent,
        ChangecolorDirective // custom directive declared as part of module
      ],
      imports: [
        BrowserModule,
        CommonModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    <!-- table displaying values from objects in users array -->
        <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Users Details</h3>
          </div>
          <div class="panel-body">
            <section class="container">
              <h2>User Details Table</h2>
              <table class="table table-hover">
                <thead>
                  <tr>
                    <th>Index</th>
                    <!-- looping thorugh array which contains keys of object and display as heading -->
                    <th *ngFor='let key of keys'>{{key}}</th>
                  </tr>
                </thead>
                <tbody>
                  <!-- looping through the users array and displaying values with the index with custom directive applied-->
                  <tr *ngFor='let user of users; index as i' appChangecolor [index]="i" [ngStyle]="{'color': color}">
                    <td>{{i+1}}</td>
                    <td>{{user.firstName}}</td>
                    <td>{{user.lastName}}</td>
                    <td>{{user.email}}</td>
                  </tr>
                </tbody>
              </table>
            </section>
          </div>
        </div>


   

最佳答案

为什么你需要一个指令,试着在组件中做:

onMouseEnter(index) {
  if (index % 2 === 0) {
    this.color = 'green';
   } else {
    this.color = 'red';
   }
}

onMouseLeave() {
   this.color = 'black';
}

模板

<tr *ngFor='let user of users; index as i' (mouseenter)="onMouseEnter(index)" (mouseleave)="onMouseLeave()" [ngStyle]="{'color': color}">
<td>{{i+1}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
</tr>

然后尝试使用 Renderer2 和 ElementRef

this.render.setStyle(this.elementRef, 'color', this.color);

对于 ngStyle,我现在无法对其进行测试,但我认为您必须拥有 EventEmitter。这是一些简单的例子,只是为了给出方向......

@Output colorChanged: EventEmitter = new EventEmitter<string>();

@HostListener('mouseenter') bgColor() {
   ....
    this.colorChanged.emit(this.color);
   ....
}

@HostListener('mouseleave') bgColor() {
   ....
    this.colorChanged.emit(this.color);
   ....
}

<tr *ngFor='let user of users; index as i' appChangecolor [index]="i" [ngStyle]="{'color': color}" (colorChanged)="this.color=$event">

关于javascript - 为什么 ngStyle 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46275297/

相关文章:

javascript - Meteor 获取用户创建时间和电子邮件

javascript - 行更改页脚中的数据表动态总计

javascript - 展开时的 Angular Dropdown 显示在屏幕底部

reactjs - 如何轻松获取 ts 类型的 react-native element prop?

Angular 5 - 从 Url 中提取 id

typescript - 使用matb33 :collection-hooks in typescript

php - 分发时防止删除代码?

javascript - 如何在响应式导航栏上放置 Logo 图像

angular - 带有延迟操作符的单元测试 Observable

typescript - 使用 observables 跟踪 typeahead 列表中的当前位置