【发布时间】:2023-04-01 01:44:01
【问题描述】:
我创建了一个自定义指令并将 selector 值设置为“[unless-directive]”。
指令获取一个布尔值并使用它来改变视图:
import {Directive, TemplateRef, ViewContainerRef} from 'angular2/core';
@Directive({
selector: '[unless-directive]',
inputs: ['givenBoolean : myDirectiveFunction']
})
export class UnlessDirective {
private _templateRef: TemplateRef;
private _viewContainerRef: ViewContainerRef;
constructor(_templateRef: TemplateRef, _viewContainerRef: ViewContainerRef) {
this._templateRef = _templateRef;
this._viewContainerRef = _viewContainerRef;
}
set myDirectiveFunction(condition: boolean) {
!condition ? this._viewContainerRef.createEmbeddedView(this._templateRef)
: this._viewContainerRef.clear();
}
}
在我的模板中,我尝试像这样传递条件:
<div name="customDirective">
<h2>Custom Directive</h2>
<div>
Enter true or false:
<br/>
<input type="text" #condition (keyup)="0"/>
<div *unless-directive [givenBoolean]="condition.value != 'false'">
Only shown if 'false' wad enterded!
</div>
</div>
</div>
当我运行代码时出现此错误:
例外:模板解析错误:无法绑定到“givenBoolean”,因为 它不是已知的原生属性(“...仅在输入 'false' wad 时显示!”):StructualDirectivesComponent@47:39
我猜我的语法是错误的,但我找不到哪里或为什么?
我在 Angular2 Docs 上查找了它,但该示例对输入和选择器使用相同的名称,这是我试图避免的。
谁能知道更好的方法或能找到我的语法问题?
谢谢。
【问题讨论】:
-
您是否将
UnlessDirective添加到您使用它的组件的指令列表中?对我来说,这听起来好像没有添加指令。还要检查指令的构造函数是否被调用。 -
@Günter Zöchbauer 是的,我添加到使用它的组件中的指令中。这是正确的做法吗?我没有任何语法错误?对吗?
-
是的,AFAIK。您是否检查过该指令实际上已实例化?
-
我将输入和选择器更改为相同的值并且它可以工作,就像在 Angular2 Docs 中的示例中一样,但是当我将其更改回来时,仍然是相同的错误。实例化是什么意思?
标签: html angular angular2-template angular2-directives angular2-forms