Angular2: не удается разрешить все параметры для моей директивы
Я пишу директиву, которая имеет зависимости от TemplateRef<any>
а также ViewContainerRef
, Но моя директива не может вставить эти зависимости. Вот весь мой код:
main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloWorld } from './HelloWorld.directive';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, HelloWorld],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
Hello world!
<template [lcngHw]="true"><div></div></template>
`
})
export class AppComponent {
}
HelloWorld.directive.ts
import { Directive } from '@angular/core';
import { Input } from '@angular/core';
import { TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[lcngHw]'
})
export class HelloWorld{
constructor(private tf: TemplateRef<any>, private vc: ViewContainerRef){
}
@Input()
set lcngHw(value: boolean) {
if (value) {
this.vc.createEmbeddedView(this.tf);
}
else {
this.vc.clear();
}
}
}
И вот мой израненный HelloWorld.directive.js:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var core_2 = require('@angular/core');
var HelloWorld = (function () {
function HelloWorld(tf, vc) {
this.tf = tf;
this.vc = vc;
}
Object.defineProperty(HelloWorld.prototype, "lcngHw", {
set: function (value) {
if (value) {
this.vc.createEmbeddedView(this.tf);
}
else {
this.vc.clear();
}
},
enumerable: true,
configurable: true
});
__decorate([
core_2.Input()
], HelloWorld.prototype, "lcngHw", null);
HelloWorld = __decorate([
core_1.Directive({
selector: '[lcngHw]'
})
], HelloWorld);
return HelloWorld;
}());
exports.HelloWorld = HelloWorld;
Затем я запускаю свое приложение и получаю следующую ошибку:
Ошибка: (SystemJS) Не удается разрешить все параметры для HelloWorld: (?,?).
Ошибка: не удается разрешить все параметры для HelloWorld: (?,?). в CompileMetadataResolver.getDependenciesMetadata ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:14268:21) в CompileMetadataResolver.getTypeMetadata ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:14169:28) в CompileMetadataResolver.getDirectiveMetadata ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:13944:30) на eval ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:14037:51) в Array.forEach (нативный) в CompileMetadataResolver.getNgModuleMetadata ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:14031:51) в RuntimeCompiler._compileComponents ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:16721:49) в RuntimeCompiler. _compileModuleAndComponents ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:16659:39) в RuntimeCompiler.compileModuleAsync ( http: // localhost: 5000 / http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:16650:23) в PlatformRef _._ bootstrapModuleWithZone ( http://localhost:5000/node_modules/@angular/core/bundles/core.umd.js:6707:29) Оценка http://localhost:5000/ViewContainerRefApp/main.js Ошибка загрузки http://localhost:5000/ViewContainerRefApp/main.js в CompileMetadataResolver.getDependenciesMetadata ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:14268:21) в CompileMetadataResolver.getTypeMetadata ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:14169:28) в CompileMetadataResolver.getDive ( http : // http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:13944:30) на eval ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:14037:51) в Array.forEach (нативный) в CompileMetadataResolver.getNgModuleMetadata ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:14031:51) в RuntimeComp iler._compileComponents ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:16721:49) в RuntimeCompiler._compileModuleAndComponents ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:16659:39) в RuntimeCompiler.compileModuleAsync ( http://localhost:5000/node_modules/@angular/compiler/bundles/compiler.umd.js:16650:23) в PlatformRef _._ bootstrapModuleWithZone ( http://localhost:5000/node_modules/@angular/core/bundles/core.umd.js:6707:29) Оценка http://localhost:5000/ViewContainerRefApp/main.js Ошибка загрузки http://localhost:5000/ViewContainerRefApp/main.js
Я также скопировал код из этого примера и получил ту же ошибку.
Кажется, что TemplateRef<any>
а также ViewContainerRef
"s metadata
не зарегистрированы. Но я не могу выяснить причину. Кто-нибудь может мне помочь? Спасибо.
2 ответа
Вы должны использовать одну из этих опций для структурной директивы:
<div *lcngHw="true"></div>
<template [lcngHw]="true"><div></div></template>
<div template="lcngHw true"></div>
Таким образом, вы можете ввести TemplateRef
в вашем компоненте
Это также может быть полезно:
Если вы используете tsconfig.json, добавьте emitDecoratorMetaData: true
Если вы используете Visual Studio без tsConfig.json, добавьте тег TypeScriptEmitDecoratorMetadata в файл своего проекта. Примечание. Возможно, вам понадобятся дополнительные теги.
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<TypeScriptRemoveComments>false</TypeScriptRemoveComments>
<TypeScriptSourceMap>true</TypeScriptSourceMap>
<TypeScriptTarget>ES5</TypeScriptTarget>
<TypeScriptJSXEmit>None</TypeScriptJSXEmit>
<TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
<TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
<TypeScriptModuleKind>System</TypeScriptModuleKind>
<TypeScriptModuleResolution>node</TypeScriptModuleResolution>
<TypeScriptOutFile />
<TypeScriptOutDir />
<TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
<TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
<TypeScriptMapRoot />
<TypeScriptSourceRoot />
<TypeScriptExperimentalDecorators>True</TypeScriptExperimentalDecorators>
<TypeScriptEmitDecoratorMetadata>True</TypeScriptEmitDecoratorMetadata>
</PropertyGroup>