你好,首先我必须说对不起,但我不知道如何更好地表达这个问题,这就是我无法自己找到答案的原因。
我说的是如何将一个组件加载到另一个组件中,我需要在指令中指明它。这是我从头开始做的一个非常小的例子,因为我找不到正确的语法:
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 中看到的那样,组件内部有一个指令,如果我删除它,它就不起作用。我不是 100% 确定为什么,但这就是我学习的方式。
所以下一步,我想要有几个组件,所以我可以有 Prueba 和另一个添加一些额外的东西(对于初学者来说,另一个“短语”,但我的想法是添加类似于 THIS 的东西:http://plnkr.co/edit/SVPNwk?p=preview)。然而,我发现自己无法找到正确的语法,我尝试的任何事情都会使这个简单的示例失败。
正如我所说,我不明白我错过了什么,我有一个新组件,我导入它,我使用选择器,等等,但它只是爆炸。我缺少哪些概念?
如果我仍然没有足够恰本地解释自己,这就是我正在谈论的理论概念:
angular.io/docs/ts/latest/cheatsheet.html(我不能发布两个以上的链接......无论如何它是@Component部分,这是我正在检查的文档)。
最佳答案
在 Angular2 中,组件和指令之间存在差异:
- 组件 收集具有某些属性和处理(组件类)的 View (模板)
- 有两种指令:
- 属性指令。它改变了 DOM 元素的外观或行为
- 结构指令。它通过添加和删除 DOM 元素来更改 DOM 布局。
一个组件可以使用它的选择器在另一个组件中使用。您需要在容器组件的 directives
属性中明确定义它。虽然该属性称为 directives
,但您可以将组件和指令放入其中。您还可以向组件提供参数并对其事件使用react。
这是一个示例:
子组件
@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
属性。如果组件/指令不是平台组件/指令,则需要明确定义到该指令中。否则,组件/指令将不适用。
这个属性可以接受多个值,因为它是一个数组:
@Component({
selector: 'comp',
template: `
<div>
<sub></sub>
<another></another>
</div>
`,
directives: [ SubComponent, AnotherComponent ]
})
export class ContainerComponent {
}
关于javascript - 如何向单个组件添加多个指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36331108/