没有装饰器的组件的角度依赖注入

时间:2019-01-03 11:18:32

标签: angular angular-components angular-dependency-injection

我遇到了一些代码,其中某些组件可以访问其父组件实例,但是我不知道“注入”是如何发生的。

我希望代码能够适合其中的scenarios之一,但是在父组件中没有专用的属性绑定,在子组件中没有@Injectable装饰器,在子组件中没有@Host。然后, Angular如何知道它必须将父组件实例作为子组件构造器中的第一个参数注入?这是因为父组件和子组件属于同一模块吗?这里是否发生任何隐式行为?


相关代码片段

子组件从通用抽象类继承父实例
(此类与角度分量无关)

// The "parent" component file
import {GraphComponent} from "./graph.component";

export abstract class GraphElement implements OnDestroy {
    graph: GraphComponent;

    constructor(graph: GraphComponent, element: ElementRef) {
        this.graph = graph;
        // misc instructions …
    }
    …
}

孩子有类似的@component装饰器和构造器

@Component({
  selector: 'g[lines]',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `` // Empty string (not truncated), by the way why not using a directive instead?
})
export class LineComponent extends GraphElement {

    constructor(graph: GraphComponent, element: ElementRef) {
        super(graph, element);
        console.log(graph) // Does output the "parent" graph component instance to the console
    }

“父级”组件声明

@Component({
  selector: 'graph',
  styleUrls: ['./graph.component.scss'],
  providers: [MiscService],
  // Truncated template
  template: `
         <svg>
             …
             <svg:g>
                 // The only input is pure d3Js chart data
                 <svg:g *ngIf="linesData" [lines]="linesData" />
             </svg:g>
             …
         </svg>
  `
})
export class GraphComponent implements AfterViewInit, OnDestroy {
    constructor(public elementRef: ElementRef, changeDetectorRef: ChangeDetectorRef /*, misc unrelated services */) {
        this.element = elementRef.nativeElement;
        // …
    }
    …
}

0 个答案:

没有答案