如何使用结构指令更改边框?



我正在尝试创建一个做两件事的角度指令。

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 的结构,通常是通过添加、删除或操作元素。

在这种情况下,创建属性指令以将按钮附加到主机元素是不合适的。不是吗?

尝试如下:

演示

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 注释,并且没有 style 属性。

要附加按钮,您可以遵循以下结构指令的非常好示例: 使用结构指令将组件添加到模板引用

对于边框,您需要执行以下操作:

创建指令:

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 声明和导出此指令,以便应用程序模块可以全局加载和导入它。

共享模块

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> 

演示

最新更新