如何在属性指令中注入指令或组件?

时间:2016-06-14 23:50:46

标签: dependency-injection typescript angular angular2-directives

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-componentmyOtherDirective,当然浏览器也不识别它们。我有两个问题:

  1. 如何在属性指令中注入另一个指令或组件?

  2. 我在这里滥用了属性指令吗?组件是否更适合?

1 个答案:

答案 0 :(得分:3)

这是对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个标记。

注释directive的成员Component有点误导。您可能认为此处只能引用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。这对我非常有帮助。

相关问题