繁体   English   中英

Angular无法绑定到“ dirUnless”,因为它不是已知属性

[英]Angular Can't bind to 'dirUnless' since it isn't a known property

我想添加自定义,除非*ngIf相反的directive

这是我的代码:

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

@Directive({
    selector: '[dirUnless]'
})
export class UnlessDirective {
    @Input() set unless(condition: boolean) {
        if (!condition) {
            this.vcRef.createEmbeddedView(this.templateRef);
        } else {
            this.vcRef.clear();
        }
    }

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

另外,我还添加了下一个html

<div *ngIf="switch"> Conditional Text IF</div>
<div *dirUnless="switch">Conditional Text UNLESS</div>

因此,当我单击switch时,仅应显示一个div

但是我有下一个错误:

未处理的承诺拒绝:模板解析错误:无法绑定到“ dirUnless”,因为它不是“ div”的已知属性。 (”

有两种选择:

1)将@Input名称从unless更改为dirUnless

@Input() set dirUnless(condition: boolean) {

2)使用别名

@Input('dirUnless') set unless(condition: boolean) {

柱塞示例

问题是我没有在NgModule上声明我的指令

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM