【问题标题】:custom directive not working自定义指令不起作用
【发布时间】:2018-06-01 20:01:08
【问题描述】:

我正在尝试为编辑/私人信息创建指令。 如果未提供某些信息,则应显示黑框(就好像内容存在但用黑框使其不可见)

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

@Directive({
selector: '[appRedactedContent]'
})
export class RedactedContentDirective implements OnInit {
min = 75;
max = 150;
width = this.randomIntFromInterval(this.min, this.max);
constructor(private el: ElementRef,
          private renderer: Renderer) {
          }
ngOnInit() {
  this.renderer.setElementStyle(
        this.el.nativeElement, 'background-color', 'blue !important');
        this.renderer.setElementStyle(this.el.nativeElement, 'width', 
                                      this.width.toString());
  }

randomIntFromInterval(min: number, max: number): number {
 return Math.floor(Math.random() * (max - min + 1) + min);
}
}

html

<a appRedactedContent></a>

当我打开我的开发者工具时,我可以看到正在添加的样式,但是我在浏览器中看不到 a-tag 的蓝色框

【问题讨论】:

  • 删除!important并将px添加到宽度

标签: angular angular2-directives angular-directive custom-directive


【解决方案1】:

标签作为内联的默认显示,你不能强制是宽度也不是高度。

由于您的 a 标签没有内容,因此宽度为 0,然后您看不到它

如果你想强制宽度,你必须将它的显示设置为 inline-block

ref to HTML specs

【讨论】:

    猜你喜欢
    • 2015-11-02
    • 1970-01-01
    • 2019-08-15
    • 2016-12-29
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多