我正在尝试创建一个做两件事的角度指令。
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
我怎么能改变样式并使用结构指令将另一个元素附加到主机?
[编辑]由于大多数答案都建议我创建一个属性指令,我只想发布有关结构指令的angular文档中的语句。
它们通常通过添加,移除或操纵元素来塑造或重塑DOM的结构。
在这种情况下,创建属性指令以将按钮附加到主机元素是不正确的。不是吗?
试试这样:
mydirective.ts:
import { Directive, TemplateRef, ElementRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appMydirective]'
})
export class MydirectiveDirective {
constructor(private el: ElementRef) {
console.log(this.el.nativeElement)
el.nativeElement.style.border = '2px solid red';
let bt = document.createElement("button");
var btContent = document.createTextNode("my Button");
bt.appendChild(btContent);
bt.style.cssFloat = 'right'
this.el.nativeElement.append(bt)
}
}
HTML:
<div appMydirective>
<h1> some value </h1>
</div>
事实上,我会为此使用结构指令。
但templateRef.elementRef.nativeElement只是一个html注释,并且没有样式属性。
要附加按钮,您可以按照结构指令的这个非常好的示例:Adding a Component to a TemplateRef using a structural Directive
对于边框,您需要执行以下操作:
创建指令:
import { Directive, ElementRef, Renderer } from '@angular/core';
// Directive decorator
@Directive({ selector: '[myDirective]' })
// Directive class
export class MyDirective {
constructor(el: ElementRef, renderer: Renderer) {
// Use renderer to render the element with styles
renderer.setElementStyle(el.nativeElement, 'border', '1px solid red');
}
}
您需要通过SharedModule声明并导出此指令,以便app模块可以全局加载和导入它。
Shared.module
import { NgModule } from '@angular/core';
import { MyDirective } from './my-directive.directive';
@NgModule({
declarations: [
MyDirective
],
exports: [
MyDirective
]
})
export class SharedModule{}
然后在app.module中导入共享模块
然后使用如下:
<div myDirective>
<h1> some value </h1>
</div>