简体   繁体   English

在Angular 2中将属性指令转换为元素

[英]Converting Attribute Directive to Element in Angular 2

I'm trying get my head around this Attribute Directive provided in Angular 2. 我正在努力了解Angular 2中提供的此属性指令。

Initially I thought I can create only directives using Attribute, but then when I tried few things I'm able to create directives using Elements also. 最初,我以为只能使用Attribute创建指令,但是当我尝试了几件事后,也能够使用Elements创建指令。

Please refer following code where I'm able to create a Element directive 请在我能够创建Element指令的地方参考以下代码

@Directive({
    selector: 'myDir'
})
export class MyDirective implements OnInit {
    @Input() prop1: boolean;
    @Input() prop2: boolean;
    constructor() {
    }
    ngOnInit(): void {
        console.log(this.prop1);
        console.log(this.prop2);
    }
}

Can use it like below 可以像下面一样使用

<myDir [prop2]="true">Hello World</myDir>

Rendered HTML 呈现的HTML

在此处输入图片说明

Questions: 问题:

  • Why it is called Attribute directive if it is based on the selector you provide. 如果它基于您提供的选择器,为什么将其称为Attribute指令。

    For example: 例如:

    • if I'm providing [myDir] then I can use it as attribute 如果我提供[myDir],则可以将其用作属性
    • But if I'm using myDir as selector this will make it as element directive. 但是,如果我使用myDir作为选择器,它将使其作为元素指令。

I's called attribute directive only if you're using an attribute selector. 仅当您使用属性选择器时,我才称为属性指令。

If you're using a class or element selector it's not an attribute directive anymore. 如果您使用的是类或元素选择器,则不再是属性指令。

In general directives are just called directives. 通常,伪指令仅称为伪指令。

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

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