【问题标题】:What are the examples of attribute directive属性指令的例子有哪些
【发布时间】:2017-05-15 18:48:14
【问题描述】:

我不知道什么时候该去

  • 创建属性指令,
  • 意识到我需要创建属性指令,
  • 使用输入和输出属性

属性指令需要什么?

我倾向于将所有逻辑包含在一个组件中,我知道它的定义,但实际上我找不到示例。

最佳做法是什么?

【问题讨论】:

标签: javascript angular typescript attributes angular2-directives


【解决方案1】:

指令可用于操作 DOM 元素。当您想要制作可供您团队或世界中的其他程序员使用的自定义(第三方)指令时,它非常有用。

基本上有三种类型的指令。

1) 结构指令
2) 属性指令
3) 组件指令(带模板)


1) 结构指令 通常操纵视图/模板的结构。例如。 *ngFor 将根据您的列表计数生成元素。 *ngIf 将根据传递的值显示/隐藏视图


2) 属性指令 允许您在 DOM 元素上添加属性,然后您可以使用该 DOM 元素做很多事情

例如。

<p myColor >Color me!</p>    //<<< this helps you to grab DOM element using ElementRef and then I'll color it as shown below.

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
  selector: '[myColor]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'red';  
  }
}

这里 myColor 只是一个 attribute directive,因为它作为 attribute 添加到 DOM 元素中,但是这个 属性不接受任何值。

现在让我们为 myColor 属性添加一个值,

<p [myColor]="color">Highlight me!</p>   


@Input :这里我们传递 color variable(Angular2 bindings) 所以在指令中我们必须有一个机制来接收它。所以我们应该使用 @Input API 因为我们要从父组件中获取价值(你可以将指令视为父组件的子组件)
@Output :如果您希望指令发出一些应该由父组件接收的值,那么您应该使用 @Output API

【讨论】:

  • 带有属性指令我们只能改变它的样式而不改变它吗?
猜你喜欢
  • 2015-10-27
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多