【发布时间】:2019-02-04 01:49:25
【问题描述】:
我正在尝试创建一个执行两件事的角度指令。
1. change border of the host element
2. append a button at the end of the host element
到目前为止,我正处于必须设置宿主元素边框的第一步。
HTML
<div *myDirective
<h1> some value </h1>
</div>
指令
export class MyDirective{
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) {
this.templateRef.elementRef.nativeElement.style['border'] = '1px solid red';
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
现在当我将此指令添加到 div 元素时,我收到以下错误,
Cannot set property 'border' of undefined
如何更改样式并使用结构指令将另一个元素附加到主机?
[编辑] 由于大多数答案都建议我创建一个属性指令,所以我只想从角度文档中发布关于结构指令的声明。
它们塑造或重塑 DOM 的结构,通常是通过添加、移除或操作元素。
在这种情况下,创建属性指令以将按钮附加到宿主元素是不合适的。不是吗?
【问题讨论】:
-
你不应该使用
ElementRef而不是TemplateRef吗?