组件和指令有什么区别? [英] What is the difference between component and directive?

查看:46
本文介绍了组件和指令有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 Angular 2.

I have just started working with Angular 2.

我想知道 Angular 2 中的组件和指令之间有什么区别?

I was wondering what are the differences between components and directives in Angular 2?

推荐答案

根据文档,Angular2 中基本上有三种类型的指令.

Basically there are three types of directives in Angular2 according to documentation.

  • 组件
  • 结构指令
  • 属性指令

它也是一种带有模板、样式和逻辑部分的指令,是Angular2中最著名的指令类型.在这种类型的指令中,您可以在 @Component 注释中使用其他指令,无论它是自定义的还是内置的,如下所示:

It is also a type of directive with template,styles and logic part which is most famous type of directive among all in Angular2. In this type of directive you can use other directives whether it is custom or builtin in the @Component annotation like following:

@Component({
    selector: "my-app"
    directives: [custom_directive_here]
})

在您的视图中使用此指令:

Use this directive in your view as:

<my-app></my-app>

对于组件指令,我找到了最好的教程 在这里.

For the component directive i have found best tutorial here.

*ngFor*ngIf一样,用于通过添加和删除DOM元素来改变DOM布局.在此解释

Like *ngFor and *ngIf, used to change the DOM layout by adding and removing DOM elements. explained here

它们用于通过应用一些功能/逻辑为现有元素提供自定义行为或样式.ngStyle 是一个属性指令,用于动态地为元素提供样式.我们可以创建自己的指令并将其用作某些预定义或自定义元素的属性,以下是一个简单指令的示例:

They are used to give custom behavior or style to the existing elements by applying some functions/logic. Like ngStyle is an attribute directive to give style dynamically to the elements. We can create our own directive and use this as attribute of some predefined or custom elements, here is the example of a simple directive:

首先我们必须从 @angular/core

import {Directive, ElementRef, Renderer, Input} from '@angular/core';

@Directive({
  selector: '[Icheck]',
})
export class RadioCheckbox {
   // custom logic here...
}

我们可以在如下所示的视图中使用它:

We can use this in the view as shown below:

<span Icheck>HEllo Directive</span>

有关更多信息,您可以阅读官方教程此处这里

For more info you can read the official tutorial here and here

这篇关于组件和指令有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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