简体   繁体   English

如何在Angular 4及更高版本的组件上使用自己的自定义指令

[英]How to use my own custom directive on my component in angular 4 and above

I want use like this: 我想这样使用:

<v-button uppercase>test</v-button>

my component and directive as follows: 我的组件和指令如下:

@Component({
    selector: "v-button",
    template: "<button class="if component has uppercase directive set 'uppercase css class' here"></button>"
})
export class ButtonComponent{
}

@Directive({
   selector : "[uppercase]"
})
export class UppercaseDirective{
}

and i expect this: 我期望这样:

<button class="uppercase">test</button>

thanks for helps. 感谢您的帮助。

Solution : for thank you @Wand Maker for giving me the tip 解决方案:感谢@Wand Maker给我小费

@Component({
selector: "v-button",
template: "<button #uppercaseFlag class="if component has uppercase directive set 'uppercase css class' here"></button>"
})
export class ButtonComponent{
 @ViewChild('uppercaseFlag') uppercaseElement: ElementRef;
}

@Directive({
 selector : "[uppercase]",
 providers : [ButtonComponent]
})
export class UppercaseDirective{
 ngAfterContentInit(): void {
 this.renderer.addClass(this.button.uppercaseElement.nativeElement, "uppercase");
 }
 constructor(private readonly renderer: Renderer2, private readonly button: ButtonComponent) { }
 }

The directive needs to access the button child and add class attribute to it. 该指令需要访问button子项并为其添加类属性。 To do that, you can inject ElementRef in directive constructor to obtain reference to host element v-button , and then, wait for the component to get initialized - after which in ngAfterContentInit method - you can assign uppercase style to first child of v-button - which will be a button element. 为此,您可以在指令构造函数中注入ElementRef以获得对宿主元素v-button引用,然后等待组件被初始化-然后在ngAfterContentInit方法中,您可以将uppercase样式分配给v-button第一个子ngAfterContentInit -这将是一个button元素。 If you do change template of v-button , you may have to adjust this part of the code. 如果确实要更改v-button模板,则可能必须调整代码的这一部分。

Here is the directive code: 这是指令代码:

@Directive({
   selector : "[uppercase]"
})
export class UppercaseDirective implements  AfterContentInit {
  constructor(private el: ElementRef) {
  }

  ngAfterContentInit() {
    this.el.nativeElement.children[0].className='uppercase';
  }
}

In addition, you may also want to update your v-button template to have ng-content so that buttons can be assigned a text/name like this: 另外,您可能还希望将v-button模板更新为具有ng-content以便可以为按钮分配如下文本/名称:

 <v-button uppercase>Test</v-button>

Here is updated component code: 这是更新的组件代码:

@Component({
    selector: "v-button",
    template: "<button><ng-content></ng-content></button>"
})
export class ButtonComponent{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM