【问题标题】:custom directive - Angular 2/4/5自定义指令 - Angular 2/4/5
【发布时间】:2018-11-15 20:19:58
【问题描述】:

目前使用 Angular 5 cli。 我不知道为什么我的自定义指令不起作用。甚至没有在我的控制台中显示错误。我正在尝试一些样式来保持完整的图像宽度。

到目前为止。

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

@Directive({
  selector: '[fullWidthImg]'
})
export class MyStyleDirective {

  constructor(private el: ElementRef, private renderer:Renderer){
    renderer.setElementStyle(el.nativeElement,'background-image', 'url("https://mdbootstrap.com/img/Photos/Horizontal/Nature/full page/img(20).jpg")')
    renderer.setElementStyle(el.nativeElement,'height', '100%")')
    renderer.setElementStyle(el.nativeElement,'background-position', 'center')
    renderer.setElementStyle(el.nativeElement,'background-repeat', 'no-repeat')
    renderer.setElementStyle(el.nativeElement,' background-size','cover')
  }

}

从其他资源复制

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

@Directive({ 
     selector: '[fullWidthImg]' 
})
export class MyStyleDirective implements AfterViewInit {
    constructor(private elRef: ElementRef) {
    }
    ngAfterViewInit(): void {
       this.elRef.nativeElement.style.backgroundImage = 'url("https://mdbootstrap.com/img/Photos/Horizontal/Nature/full page/img(20).jpg")';
       //this.elRef.nativeElement.style.fontSize = '20px';
    }       
} 

html

<div fullWidthImg></div>

哪里做错了。如果可能,请提供活生生的例子或很好的资源来理解自定义指令

谢谢

【问题讨论】:

  • 你在app.module中导入了吗?
  • 是的,我在 app.module.ts 中做了
  • @worstCoder 你应该设置heightwidthdiv 标签否则不应该显示图像
  • 我应该为宽度增加多少高度?

标签: angular angular5 custom-directive


【解决方案1】:

我应该为高 n 宽度增加多少?

【讨论】:

    【解决方案2】:

    试试这个:

    <div fullWidthImg [ngStyle]="{'height': '200px', 'width':'200px'}"> </div>
    

    其余代码都在工作,只需更改 div 标签! 这是工作示例:Image display

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-17
      • 2017-02-07
      • 1970-01-01
      • 2018-03-31
      • 2018-11-05
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多