簡體   English   中英

Angular4基本指令不起作用

[英]Angular4 basic directive not working

我試圖使用自定義指令更改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() {}
}

任何想法為什么不使“面板 - 默認”藍色的背景?

仔細檢查一下我的代碼之后,我發現了兩件事

  1. 導出自定義指令:

    出口類CardHoverDirective {..

  2. 導入並在app.module.ts中聲明它

工作得很好,但這是另一種方法:

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

}

https://plnkr.co/edit/A4jsawihIpO0sCoRVbCm

在你的指令中使用 -

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM