简体   繁体   English

Angular中的依赖注入组件

[英]Dependency inject components in Angular

Is it possible to somehow dependency inject components in Angular?是否可以在 Angular 中以某种方式依赖注入组件? I would like to be able to do something similar to what you can do with services eg:我希望能够做一些类似于你可以用服务做的事情,例如:

my.module.ts:
providers: [
   {
      provide: MyService,
      useClass: CustomService
   }
]

I have tried to use *ngIf="condition" in a wrapper component, but it will then complain about services not being provided for the components I do not wish to use.我曾尝试在包装组件中使用 *ngIf="condition",但它会抱怨没有为我不想使用的组件提供服务。

It is fully possible if you have parent-child relationship between the component and injecting component.如果组件和注入组件之间存在父子关系,则完全有可能。 so if you have the structure like this所以如果你有这样的结构

@Component( {
    selector:"app-parent",
    template:" <app-child> </app-child>"
 } )
export class ParentComp { ...}

you could inject parent-component inside the child component via dependency injection您可以通过依赖注入在子组件中注入父组件

@Component({
    selector:"app-child",
     template:"I am child"
 })
export class ChildComponent{
    constructor(private parentComp:ParentComponent){
}
}

Angular DI will now that you are asking for parent component that child component lives in and will inject it for you. Angular DI 现在您正在请求子组件所在的父组件,并将为您注入它。

If you want to inject component not parent-child relationship like, so for example you want to inject the sidenav component into the some table component that lives outside the sidenav, it is hardly achiavable (not recommended also), but possible.如果您想注入组件而不是父子关系,例如,您想将 sidenav 组件注入到位于 sidenav 之外的某个 table 组件中,这是几乎无法实现的(也不推荐),但可能。 if you want to do that, you should probably create shared service, that will share the states between these components.如果你想这样做,你可能应该创建共享服务,它将在这些组件之间共享状态。

Sure, you can provide any value (const, function, class) for the particular injection token.当然,您可以为特定的注入令牌提供任何值(const、function、类)。 You can find some examples with components providing when we are going to make ControlValueAccessor当我们要制作ControlValueAccessor时,您可以找到一些组件提供的示例

@Component({
providers: [     
   { 
     provide: NG_VALUE_ACCESSOR, 
     useExisting: forwardRef(() => CustomInputComponent),
     multi: true     
    }   
]
})
export class CustomInputComponent {...}

You can create your own injection token and provide any stuff you want and components also.您可以创建自己的注入令牌并提供您想要的任何东西和组件。

/* In tokens.ts */ 
const MY_TOKEN_NAME = new InjectionToken<MyAmazingComponent>('MY_TOKEN_NAME')

/* In module */    
providers: [
  { provide: MY_TOKEN_NAME, useClass: MyAmazingComponent }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM