自定义Angular结构指令仅适用于星号语法

时间:2018-08-16 04:26:50

标签: angular angular-template

我创建了一个Angular结构指令,但是它仅适用于*语法,而不适用于'expanded <ng-template>语法。

快速reminder

当您在结构指令(例如*ngIf="xxx")前加星号时,模板编译器会对其进行扩展,因此以下等效:

<p *ngIf="condition">
  Our heroes are true!
</p>

<ng-template [ngIf]="condition">
  <p>
    Our heroes are true!
  </p>
</ng-template>

所以我创建了自己的指令(基于ngIf源代码):

@Directive({
    selector: '[featureBoxLoader]'
})
export class FeatureBoxLoaderDirective {

    private _thenTemplateRef: TemplateRef<any>|null = null;

    constructor(private _viewContainer: ViewContainerRef, 
                private templateRef: TemplateRef<any>) 
    {
        this._thenTemplateRef = templateRef;
    }

    ngOnInit()
    {
        alert('yes it works!');
        this._viewContainer.createEmbeddedView(this._thenTemplateRef, { $implicit: { numbers: [1, 2, 3] } } );
    }
}

指令在我的模块中声明,当我像这样使用它时,它可以正常工作:

  <div *featureBoxLoader>
     This is my feature box
  </div>

但是,当我这样做时,我得到一个错误:

 <ng-template [featureBoxLoader] let-data></ng-template>

错误是:

  

无法绑定到“ featureBoxLoader”,因为它不是的已知属性   'ng-template'。   1.如果'featureBoxLoader'是Angular指令,则将'CommonModule'添加到该组件的'@ NgModule.imports'中。   2.要允许任何属性,请在此组件的'@ NgModule.schemas'中添加'NO_ERRORS_SCHEMA'。

发生了什么事?显然可以找到它,但是我需要对<ng-template>使用let语法。

1 个答案:

答案 0 :(得分:2)

区别在于,在*ngIf示例中,您提供了一个参数(在ng_if directive implementation中还提供了相应的@Input参数)。

[ngIf]="condition"

仅在没有条件的情况下应用指令时,不需要括号。

所以正确的语法就是:

<ng-template featureBoxLoader let-data></ng-template>
相关问题