如何将多个指令添加到单个组件中

How to add several directives to a single component

本文关键字:单个 组件 添加 指令      更新时间:2023-10-16

你好,首先我必须说对不起,但我不知道如何更好地表达这个问题,这就是我自己找不到答案的原因。

我所说的是如何在另一个组件中加载一个组件,我需要在指令中指出它。这里有一个非常小的例子,我从头开始做,因为我找不到正确的语法:

http://plnkr.co/edit/gFsqGJmmayOsewL3EfLf

import {Component} from 'angular2/core'
import {Prueba} from './prueba'
@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <prueba></prueba>      
    </div>
  `,
  directives: [Prueba]
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }
}

因此,正如您在app.ts中看到的那样,组件内部有一个指令,如果我删除它,它将不起作用。我不能百分之百确定为什么,但这是我学习的方式。

所以下一步,我想有几个组件,这样我就可以有Prueba和另一个添加额外内容的组件(对于初学者来说,是另一个"短语",但想法是添加类似于THIS的内容:http://plnkr.co/edit/SVPNwk?p=preview)。然而,我发现自己找不到正确的语法,我尝试的任何东西都会使这个简单的例子失败。

正如我所说,我不明白我缺少了什么,我有了一个新组件,我导入了它,我使用了选择器,等等,但它只是爆炸了。我缺少什么概念?

如果我仍然没有正确地解释自己,这就是我所说的理论概念:

angular.io/docs/ts/latest/cheatsheet.html(我不能发布两个以上的链接……无论如何,这是@Component部分,这是我正在查看的文档)。

在Angular2中,组件和指令之间存在差异:

  • 组件收集具有一些属性和处理(组件类)的视图(模板)
  • 有两种指令:
    • 属性指令。它更改DOM元素的外观或行为
    • 结构指令。它通过添加和删除DOM元素来更改DOM布局

一个组件可以使用其选择器在另一个组件中使用。您需要在容器组件的directives属性中明确定义它。尽管该属性被称为directives,但您可以在其中放入组件和指令。您还可以为组件提供参数,并对其事件作出反应。

这是一个示例:

  • 子组件

    @Component({
      selector: 'sub',
      template: `
        <div>Sub</div>
      `
    })
    export class SubComponent {
    }
    
  • 集装箱组件:

    @Component({
      selector: 'comp',
      template: `
        <div>
          <sub></sub>
        </div>
      `,
      directives: [ SubComponent, AnotherComponent ]
    })
    export class ContainerComponent {
    }
    

指令将应用于同样基于选择器的现有元素。

这是一个示例:

  • 子组件

    @Directive({
      selector: '[dir]'
    })
    export class DirDirective {
      constructor(el: ElementRef) {
        // el.nativeElement corresponds to the DOM element
        // the directive applies on
        el.nativeElement.style.backgroundColor = 'yellow';
      }
    }
    
  • 集装箱组件:

    @Component({
      selector: 'comp',
      template: `
        <div dir>Some text</div>
      `,
      directives: [ DirDirective ]
    })
    export class ContainerComponent {
    }
    

directives属性

详细介绍directives属性。如果组件/指令不是平台指令,则需要在该指令中显式定义。否则,组件/指令将不适用。

这个属性可以接受几个值,因为它是一个数组:

@Component({
  selector: 'comp',
  template: `
    <div>
      <sub></sub>
      <another></another>
    </div>
  `,
  directives: [ SubComponent, AnotherComponent ]
})
export class ContainerComponent {
}