【发布时间】:2020-09-02 00:11:57
【问题描述】:
我已经定义了一个自定义属性指令:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '.vvdirective'
})
export class VVdirectiveDirective {
constructor(private elRef: ElementRef) {}
ngOnInit() {
this.elRef.nativeElement.style.backgroundColor = "gray";
this.elRef.nativeElement.style.color = "navy";
console.log("vv directive works!!")
}
}
它将共享“vvdirective”CSS 类的元素更改为灰色背景和深蓝色字体颜色。它还会打印一条控制台消息。
它适用于传统用例:
<div class="vvdirective">My custom attribute directive works in a plain old fashion way !</div>
但是
当我想在组件中使用这个指令时:
HTML:
<div [ngClass]="klass" >My custom attribute directive works even embedded in a component</div>
&TS:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-vvdiv',
templateUrl: './vvdiv.component.html',
styleUrls: ['./vvdiv.component.scss']
})
export class VvdivComponent implements OnInit {
@Input() klass: string;
constructor() { }
ngOnInit() {
}
}
&在APP TS中调用:
<app-vvdiv klass="vvdirective"></app-vvdiv>
它不起作用(背景/字体颜色不改变并且不打印控制台消息):
应该是这样的:
令我惊讶的是,最后两个代码示例(一个带有老式指令调用的一个,一个通过组件调用的一个)都有 CSS 类:
但只有第一个(未嵌入到组件中)受指令更改的影响。
看起来在后一种情况下组件中使用的 ngClass 指令,工作方式不同。
可能和app的生命周期有关,我不知道。
所以如果你知道如何同时使用 ngClass 和我的自定义指令来制作组件,我会密切关注你的回答!
这里是 PLUNKER:plunker
这里是 GITHUB 存储库:git repo
最好的,
【问题讨论】:
-
正如你所描述的,它看起来与这些功能讨论相似,但很少见 github.com/angular/angular/issues/8785 并且尚未计划实施
-
我使用的另一个链接:stackoverflow.com/questions/46302684/…
标签: angular angular2-directives custom-directive