【发布时间】: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 你应该设置
height和width到div标签否则不应该显示图像 -
我应该为宽度增加多少高度?
标签: angular angular5 custom-directive