gpt4 book ai didi

html - angular2 自定义指令输入语法

转载 作者:太空狗 更新时间:2023-10-29 18:14:25 24 4
gpt4 key购买 nike

我创建了一个自定义指令并将 selector 值设置为“[unless-directive]”。

该指令获取一个 bool 值并使用它来改变 View :

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>

当我运行代码时出现此错误:

EXCEPTION: Template parse errors: Can't bind to 'givenBoolean' since it isn't a known native property (" ... Only shown if 'false' wad enterded!"): StructualDirectivesComponent@47:39

我想我的语法有误,但我找不到哪里或为什么?

我在 Angular2 Docs 上查了一下,但该示例对输入和选择器使用相同的名称,这是我试图避免的事情。

谁能知道更好的方法或者能找到我的语法问题?

谢谢。

最佳答案

* prefix syntax is only a syntatic sugar .它扩展了指令声明。

The * prefix syntax is a convenient way to skip the <template> wrapper tags and focus directly on the HTML element to repeat or include. Angular sees the * and expands the HTML into the <template> tags for us.

这记录在 * and <template> 中和 Directive decorator/Lifecycle hooks .

因此,在您的情况下,[givenBoolean]属性不应出现在指令中。换句话说,这:

<div *unless-directive [givenBoolean]="condition.value != 'false'">
Only shown if 'false' wad enterded!
</div>

实际上变成了:

<template [unless-directive]="">
<div [givenBoolean]="condition.value != 'false'">
Only shown if 'false' wad enterded!
</div>
</template>

givenBoolean不是组件中的属性(不是指令),就会出现错误。

因此,如果您想要自定义行为,我建议您尝试使用扩展版本,只有在它起作用后,您才能转到 *语法,推理起来会更简单。

关于html - angular2 自定义指令输入语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35539498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com