简体   繁体   中英

What is the type of angular 2 components if they are decorated?

I need to have a map of different angular components. This is the map:

  private modals: MapOf<any> = {
    addAttribute: AddAttributeModalComponent,
    editAttribute: EditAttributeModalComponent,
    requestUnit: RequestUnitModalComponent,
    requestAttribute: RequestAttributeModalComponent
  };

As you can see, I have a generic type MapOf. This is it:

export interface MapOf<T> {
  [key: string]: T;
}

Right now I am confused with < any >, because clearly this is a map of components. But I don't know how to set this type and I couldn't find the answer.

ComponentRef doesn't fit here, because it asks for a reference anyway. Type Component doesn't fit also, because my components are decorated and they contain some methods which are not present on 'pure' Component.

Any ideas?

Decorators don't change the type of the class. If you just want to avoid using the type any , have each component class to extend the same abstract class or implement the same interface. Then you can use this new type as the generic one. For example,

class AddAttributeModalComponent implements MyInterface{...}

MapOf<MyInterface> = {...}

The other option to try would be to create a new union type:

type MyNewType = AddAttributeModalComponent | 
                 EditAttributeModalComponent |
                 RequestUnitModalComponent |
                 RequestAttributeModalComponent;

MapOf<MyNewType> = {...};

Short answer: There're no such thing like that.

Long Answer: We define the Component by using the @Component({...}) decorator to provide some metadata about the Component . Angular will use that metadata to create the View , which is a low-level abstraction of the Component we used to know.

So, the below Component interface for the @Component decorator is NOT the real "component class":

import {Component} from '@angular/core';

To achieve what you're trying to do, I think Yakov Fain's answer is quite correct. Either you can create an interface or an abstract class then implement/extend your component classes from there.

If you want to know more about the view, there're some nice articles by Ng Wizard about this topic: https://blog.angularindepth.com/exploring-angular-dom-abstractions-80b3ebcfc02 https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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