简体   繁体   English

Angular4基本指令不起作用

[英]Angular4 basic directive not working

I am trying to change the background color of a div using a custom directive, but its not working, below is the code of my component generated using angular cli. 我试图使用自定义指令更改div的背景颜色,但它不起作用,下面是使用angular cli生成的组件的代码。

import {
  Component,
  Directive,
  Renderer,
  ElementRef,
  NgModule,
  OnInit } from '@angular/core';

@Directive({
  selector:"[ccCardHover]"
})
class CardHOverDirective {
  constructor(private el: ElementRef,
              private renderer: Renderer) {
    renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'blue');
  }
}
@Component({
  selector: 'app-custom-directive',
  template: `
  <div class="panel panel-default" ccCardHover>
    <p class="panel-body">Body text</p>
  </div>`
})
export class CustomDirectiveComponent implements OnInit {
  ngOnInit() {}
}

Any ideas why is not making the background of "panel panel-default" blue? 任何想法为什么不使“面板 - 默认”蓝色的背景?

After a more careful review of my code, I noticed two things 仔细检查一下我的代码之后,我发现了两件事

  1. Export the custom directive: 导出自定义指令:

    export class CardHoverDirective { .. 出口类CardHoverDirective {..

  2. Import and declare it in the app.module.ts 导入并在app.module.ts中声明它

That works just fine, but here is another way of doing it : 工作得很好,但这是另一种方法:

@Directive({
  selector:"[ccCardHover]",
  host:{
    '[style.backgroundColor]':'"red"'
  }
})
class CardHOverDirective {

}

https://plnkr.co/edit/A4jsawihIpO0sCoRVbCm https://plnkr.co/edit/A4jsawihIpO0sCoRVbCm

in your directive use - 在你的指令中使用 -

constructor(private elRef: ElementRef) {
    elRef.nativeElement.style.backgroundColor = 'red';
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM