[英]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() {}
}
任何想法為什么不使“面板 - 默認”藍色的背景?
仔細檢查一下我的代碼之后,我發現了兩件事
導出自定義指令:
出口類CardHoverDirective {..
導入並在app.module.ts中聲明它
這工作得很好,但這是另一種方法:
@Directive({
selector:"[ccCardHover]",
host:{
'[style.backgroundColor]':'"red"'
}
})
class CardHOverDirective {
}
在你的指令中使用 -
constructor(private elRef: ElementRef) {
elRef.nativeElement.style.backgroundColor = 'red';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.