简体   繁体   English

如何在Angular 5中创建通配符指令?

[英]How do I create a wildcard directive in Angular 5?

I'd like to make a directive similar to how the attribute directive works. 我想做一个类似于属性指令工作方式的指令。 Allowing for a . 允许一个. wildcard scenario, and specifying it multiple times. 通配符方案,并多次指定。

<div [attr.width]="width" [attr.height]="height" [attr.*]="" >...

I couldn't dig up any info on the docs saying how to do this. 我无法从文档中找到任何信息来说明如何执行此操作。 Maybe this is a special exception to the framework? 也许这是框架的特殊例外?

[attr.*] , [style.*] and [class.*] aren't directives. [attr.*][style.*][class.*]不是指令。 These are so called binding targets , that make the HTML operations simpler; 这些就是所谓的绑定目标 ,它们使HTML操作变得更简单。 they are the part of Angular template engine. 它们是Angular模板引擎的一部分。

They are not only not directives, as of now it is actually not possible to make any kind of directive like that, because: 它们不仅不是指令,到目前为止,实际上不可能做出任何这样的指令,因为:

  1. There is no query selector that implements a wildcard search by HTML attribute name (it is possible to have wildcard search for the attribute value only); 没有查询选择器可以通过HTML属性名称实现通配符搜索(可以仅对属性值进行通配符搜索)。 and without this mapping angular cannot identify the directive 没有此映射,angular无法识别指令
  2. Assume point 1 can be tricked by using * as the selector (which actually also is not working), then there is another problem. 假设点1可以通过使用*作为选择器(实际上也不起作用)来欺骗,那么还有另一个问题。 The @Input decorator / @Directive's inputs property does not allow wildcard bindings to get the array of name-value properties that you would like to pass. @Input decorator / @Directive 的inputs属性不允许通配符绑定获取您要传递的名称-值属性数组。 That means you need to name each property in advance. 这意味着您需要提前命名每个属性。

So it is not really possible to get what you want. 因此,实际上不可能获得想要的东西。

However, if your list is finite, you can always create a wildcard directive and listen to your inputs: 但是,如果您的列表是有限的,则始终可以创建一个通配符指令并监听您的输入:

@Directive({ selector: '[my-attr.attr1],[my-attr.attr2],[my-attr.attr3]' })
export class SemiWildcardDirective {

  @Input('my-attr.attr1') attr1: string;
  @Input('my-attr.attr2') attr2: string;
  @Input('my-attr.attr3') attr3: string;

  // and here do whatever, e.g.
  ngOnChanges() {
    console.log(this);
  }

}

or probably you can use different selector like 或者可能您可以使用其他选择器,例如

@Directive({ selector: 'div,a,p,button,input,...' })

which could theoretically lead to performance issues. 从理论上讲,这可能会导致性能问题。

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

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