如何使用结构指令更改边框? [英] How to change border using a structural directive?

查看:81
本文介绍了如何使用结构指令更改边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create an angular directive that does two things.

 1. change border of the host element
 2. append a button at the end of the host element

截至目前,我处于第一步,必须设置宿主元素的边界.

As of now i am on the first step where i have to set the border of 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元素时,出现以下错误,

Now when i add this directive to a div element,I get the following error,

Cannot set property 'border' of undefined

如何使用结构化指令更改样式并将其他元素附加到主机?

How could i change the style and append another element to the host using structural directive?

由于大多数答案都建议我创建一个属性指令,所以我只想发布有关结构指令的角度文档中的声明.

As most of the answers are suggesting me to create an attribute directive, i just want to post the statement from angular document regarding structural directives.

它们通常通过添加,删除或操纵元素来塑造或重塑DOM的结构.

They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.

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

In that case creating attribute directive to append a button to the host element is not proper. Isn't it?

推荐答案

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

For the border you need to do the following:

创建指令:

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

Following you need to declare and export this directive via SharedModule so that the app module can load and import it globally.

Shared.module

Shared.module

import { NgModule } from '@angular/core';

import { MyDirective } from './my-directive.directive';

@NgModule({
    declarations: [
        MyDirective
    ],
    exports: [
        MyDirective
    ]
})
export class SharedModule{}

然后将共享模块导入app.module

Then import the shared module in the app.module

然后按如下所示使用它:

then use it as follows:

<div myDirective>
    <h1> some value </h1>
</div> 

演示

这篇关于如何使用结构指令更改边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆