【问题标题】:angular 6 custom element directivesangular 6 自定义元素指令
【发布时间】:2018-10-25 03:17:22
【问题描述】:

如何在 Angular 6 中创建元素指令?我了解了如何创建属性指令,但是如果我想创建自定义元素怎么办?

@Directive({
  selector: '[appCards]'//you can't do something like -- element: name
})
export class CardsDirective {

    constructor(el: ElementRef) { 
}
}

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    我尝试使用 Selector 创建一个指令,它可以工作。 Angular 太强大了。

    import {Directive, ElementRef, Input} from '@angular/core';
    
    @Directive({
      selector: '<appCards>'
    })
    export class CardsDirective {
    
        @Input() label;
        constructor(el: ElementRef) { 
          console.log('it called');
        }
    
        ngOnInit(){
          console.log(this.label);
        }
    }
    

    模板:

    <appCards label="change"></appCards>
    

    https://stackblitz.com/edit/angular-av5x68

    【讨论】:

    • 酷。谢谢。我会做更多的实验
    【解决方案2】:

    在 Angular 中,您可以通过以下方式创建元素指令

    @Directive({
      selector: 'appCards'
    })
    export class CardsDirective {
    
        constructor(el: ElementRef) { 
        }
    }
    

    您只需删除选择器中的 [] 括号,即可使其成为元素指令。

    【讨论】:

      【解决方案3】:

      根据 Angular 文档,您可以将选择器声明为以下方式之一。所以如果你想创建一个带有指令的元素,你必须将指令的选择器声明为

      选择器:'elementName'

      • 元素名称:按元素名称选择。 .class:按类名选择。
      • [属性]:按属性名称选择。 [attribute=value]:选择方式
      • 属性名称和值。 :not(sub_selector): 仅当
      • 元素与 sub_selector 不匹配。选择器1,选择器2:选择
      • 如果 selector1 或 selector2 匹配。

      https://angular.io/api/core/Directive#selector

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-30
        • 1970-01-01
        • 2016-05-13
        • 1970-01-01
        • 1970-01-01
        • 2017-08-27
        • 2019-11-19
        • 1970-01-01
        相关资源
        最近更新 更多