Angular 2中的指令是什么?

3
我不理解这两个 @Directive 和 directives: [HeroAppMainComponent] 的区别,在下面的例子中。
 @Component({
      selector: 'hero-app',
      template: `
        <h1>Tour of Heroes</h1>
        <hero-app-main [hero]=hero></hero-app-main>`,
      styles: ['h1 { font-weight: normal; }'],
      directives: [HeroAppMainComponent]
    })

and..

import { Directive, ElementRef, Input } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}
3个回答

4
简而言之,指令没有模板,而组件有。有几种指令类型:

2

实际上,Angular 2仍然存在指令。组件只是指令中最重要的一种类型,但不是唯一的一种类型。组件是带有模板的指令。但是,您仍然可以编写装饰器样式的指令,这些指令没有模板。

在这里,我们没有像Angular 1中那样的.directive函数,而是有简单的类,通过注释来赋予它们特定的行为。

导入组件的注释是:

import {Component} from 'angular2/core';

0

希望你一切都好。

根据你上面分享的代码片段,你似乎对 Angular 中的两种不同术语感到困惑。让我逐一解释一下。

你分享的第一个代码片段是:

 @Component({
  selector: 'hero-app',
  template: `
    <h1>Tour of Heroes</h1>
    <hero-app-main [hero]=hero></hero-app-main>`,
  styles: ['h1 { font-weight: normal; }'],
  directives: [HeroAppMainComponent]
})

这是一个组件的片段(正如您所看到的,选择器由“@Component”选择器表示)。组件是Angular中的基本构建块,它们提供了一种在应用程序中编写HTML代码的方式,并与一些逻辑部分(通常在TypeScript文件中)捆绑在一起,类似于以下内容:

app.component.html

<a [href] = "link">Link to...</a>

app.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  link : any = 'https: www.google.com';

  constructor(){

  }

  ngOnInit() : void {
    
  }

  ngOnDestroy(): void {

  }
}

你分享的第二个片段是一个指令(用 '@Directive' 表示)。指令只是一些逻辑,你可以编写它们来基本上操作应用程序中的 DOM 功能(例如在单击下拉菜单时更改其结构)。基本上,你只能在指令中编写逻辑而不是 HTML 部分。这里是一个基本示例:
import { Directive, ElementRef } from '@angular/core';
@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private eleRef: ElementRef) {
        eleRef.nativeElement.style.background = 'red';
    }
}

在这个指令中,我们通过设置元素的背景颜色来突出显示所选的DOM元素。
因此,基本上组件是指令的子集,您可以编写HTML(模板部分)和TS(逻辑部分)。而对于指令,您只能编写TS(逻辑部分)。
有关组件与指令的更多信息在这里。希望这可以帮助到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接