使用自定义结构指令会在控制台中引发错误?

时间:2019-06-28 15:43:50

标签: angular angular-directive

您好,我创建了一个结构指令。但是使用它会引发错误。 以下是我的结构指令代码。

import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { Account } from '../models';

@Directive({
  selector: '[pcHasCampaignBudgetEnabled]'
})
export class HasCampaignBudgetEnabledDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

 @Input() 
 set pcHasCampaignBudgetEnabled(account:Account){
    if(account && account.budget){
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear()
    }
  }

}

我在我的根模式下被声明为该结构指令。我正在从组件模板中按如下方式使用它。

  <ng-container *pcHasCampaignBudgetEnabled="currentUserAccount" pcColumnDef="budget" [sortable]="true">
      <pc-header-cell *cdkHeaderCellDef>
        {{ 'LABELS.BUDGET' | translate }} ({{ currencySymbol }})
      </pc-header-cell>
      <cdk-cell *cdkCellDef="let row">
        {{ row.budget | number }}
      </cdk-cell>
    </ng-container>

但是从开发人员工具中我遇到了以下错误。

Uncaught Error: Template parse errors:
Can't bind to 'pcHasCampaignBudgetEnabled' since it isn't a known property of 'ng-container'.
1. If 'pcHasCampaignBudgetEnabled' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
    </ng-container>

    <ng-container [ERROR ->]*pcHasCampaignBudgetEnabled="currentUserAccount" pcColumnDef="budget" [sortable]="true">
      <pc-he"): ng:///AppModule/CampaignsAwaitingPanelComponent.html@40:18
Property binding pcHasCampaignBudgetEnabled not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("
    </ng-container>

    [ERROR ->]<ng-container *pcHasCampaignBudgetEnabled="currentUserAccount" pcColumnDef="budget" [sortable]="true""): ng:///AppModule/CampaignsAwaitingPanelComponent.html@40:4
    at syntaxError (compiler.js:485)
    at TemplateParser.parse (compiler.js:24667)
    at JitCompiler._parseTemplate (compiler.js:34620)
    at JitCompiler._compileTemplate (compiler.js:34595)
    at eval (compiler.js:34496)
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (compiler.js:34496)
    at eval (compiler.js:34366)
    at Object.then (compiler.js:474)
    at JitCompiler._compileModuleAndComponents (compiler.js:34365)

非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您需要将该指令导入到component.module.ts中 像这样:

import { HasCampaignBudgetEnabledDirective } from './HasCampaignBudgetEnabledDirective ';

@NgModule({
  imports: [
    ...
  ],
  declarations: [ComponentPage, HasCampaignBudgetEnabledDirective ]
})