自定义指令 - Angular 2/4/5

时间:2018-06-06 08:16:58

标签: angular angular5 custom-directive

目前使用角度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>

我做错了。如果可能的话,请提供实时示例或良好的资源来理解自定义指令

谢谢

2 个答案:

答案 0 :(得分:1)

试试这个:

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

其余的代码只是改变div标签! 以下是工作示例:Image display

答案 1 :(得分:0)

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