Angular 2 rc 1,用TypeScript编写。
我有一个带有选择器myDirective
的属性指令。 它的目的是构建一个我经常重用的html。若要完成其工作,匹配类需要访问自定义组件以及另一个属性指令。我无法弄清楚如何在 myDirective
的类中注入属性指令或组件。
@Directive({selector: '[myDirective]'})
export class MyDirective{
constructor(private renderer:Renderer, private elementRef:ElementRef) {
let el = elementRef.nativeElement; //capture the HTML element host
let innerElement = renderer.createElement(el,'my-component',null);
renderer.setElementAttribute(innerElement,'myOtherDirective','');
}
}
用法:<div myDirective></div>
生成的 HTML: <div><my-component myOtherDirective=''></my-component></div>
问题是 Angular 模板解析器不会处理my-component
和myOtherDirective
,当然浏览器也无法识别它们。 我有两个问题:
如何在属性指令中注入另一个指令或组件?
我在这里是否滥用了属性指令?组件是否更适合?
对Directive
的误用改为创建一个Component
,以便您可以像
<my-component></my-component>
基本示例:http://learnangular2.com/components/
更新:这是示例
@Component({
selector: 'parent-component',
template: `
<div> I'm a parent component!!!
<child-component></child-component>
</div>
`,
directive: [ChildComponent]
})
@Component({
selector: 'child-component',
template: `
<div> I'm a child component!!!
</div>
`
})
- 注解的成员
directive
Component
引用ChildComponent
,即告诉ParentComponent
使用ChildComponent
的东西。 - Angular 在 ChildComponent 中看到
selector: 'child-component'
,并在模板中看到child-component
标签ParentComponent
注入它的模板。
注释Component
的成员directive
有点误导。您可能认为这里只能引用Directive
,但它也是引用Components
对于属性Directive
:
@Component({
selector: 'my-component',
template: `
<div my-directive> I'm a component with directive!!!
</div>
`,
directive: [MyDirective]
})
@Directive({
selector: '[my-directive]'
})
您可以使用属性指令传递值
<div [my-directive]="I'm a value!"> I'm a component with directive!!!</div>
查看官方文档了解详细信息:https://angular.io/docs/ts/latest/guide/attribute-directives.html
我建议您 https://youtu.be/_-CD_5YhJTA 观看此视频课程。这对我非常有帮助。