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



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. 我在这里是否滥用了属性指令?组件是否更适合?

这是

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 观看此视频课程。这对我非常有帮助。

最新更新