angular - Impune tipul în TypeScript folosind interfețe
Folosesc ceva similar cu acesta https://github.com/angular/angular/pull/11235 pentru a reda ferestre modale dinamice.
Directiva are o intrare care preia tipul Componentului pe care îl va reda:
@Directive({ selector: '[ngComponentOutlet]' })
export class NgComponentOutlet implements OnChanges {
@Input() ngComponentOutlet: Type<any>;
@Input() ngOutletInjector: Injector;
@Input() ngOutletProviders: Provider[];
@Input() ngOutletProjectableNodes: any[][];
@Output()
ngOutletCreated = new EventEmitter<ComponentRef<any>>(false);
constructor(
private _cmpFactoryResolver: ComponentFactoryResolver,
private _viewContainerRef: ViewContainerRef) { }
ngOnChanges(changes: SimpleChanges) {
if (changes.hasOwnProperty('ngComponentOutlet')) {
this._viewContainerRef.clear();
if (this.ngComponentOutlet) {
let injector = this.ngOutletInjector || this._viewContainerRef.parentInjector;
if (Array.isArray(this.ngOutletProviders) && this.ngOutletProviders.length > 0) {
injector = ReflectiveInjector.resolveAndCreate(this.ngOutletProviders, injector);
}
const cmpRef = this._viewContainerRef.createComponent(
this._cmpFactoryResolver.resolveComponentFactory(this.ngComponentOutlet),
this._viewContainerRef.length, injector, this.ngOutletProjectableNodes);
this.ngOutletCreated.emit(cmpRef);
}
}
}
}
Aș dori să aplic o interfață componentelor care poate fi utilizată astfel, astfel încât să știu că toate componentele randate dinamic au o anumită funcție, de exemplu:
export interface ModalContent {
close(): void;
}
Toate componentele care vor fi modale dinamice implementează asta:
@Component({
...
})
export class MyCustomModalComponent implements ModalContent {
close() {
...
}
}
Și apoi am pus totul împreună
@Component({
template: `<div [ngComponentOutlet]="component"></div>`,
})
export class AppComponent {
private component: ModalContent;
showModal() {
this.component = MyCustomModalComponent; <-- I get the error here
}
}
Problema mea este că primesc următoarea eroare în AppComponent:
Type 'typeof MyCustomModalComponent' is not assignable to type 'ModalContent'.
Property 'close' is missing in type 'typeof MyCustomModalComponent'.
Presupun că are legătură cu modul în care gestionez tipurile pe parcurs, dar nu sunt sigur care este problema?
EDITARE Am adăugat întreaga Directivă pentru referință
Răspuns #1
Acest cod spune că component este de tip ModalContent, ceea ce înseamnă că poate deține o instanță de ModalContent.
private component: ModalContent;
Acest cod atribuie o instanță de tip Type, nu de tip ModalContent
this.component = MyCustomModalComponent;
Acest cod ar respecta adnotările de tip
this.component = new MyCustomModalComponent();
dar nu ar trebui să instanțiezi componentele singur, ci să lași DI-ul Angular să o facă pentru tine.
Totuși, nu sunt sigur ce încerci de fapt să realizezi.
actualizare
Dacă vrei de fapt să aloci o referință tipului, asta ar trebui să funcționeze:
private component: Type<ModalContent>
