Angular 无法绑定到 'dirUnless',因为它不是已知的 属性
Angular Can't bind to 'dirUnless' since it isn't a known property
我想添加自定义,除非 directive
与 *ngIf
相反。
这是我的代码:
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
应该显示。
但是我有下一个错误:
Unhandled Promise rejection: Template parse errors: Can't bind to
'dirUnless' since it isn't a known property of 'div'. ("
有两种选择:
1) 将 @Input
名称从 unless
更改为 dirUnless
@Input() set dirUnless(condition: boolean) {
2) 使用别名
@Input('dirUnless') set unless(condition: boolean) {
问题是我没有在 NgModule 上声明我的指令
我想添加自定义,除非 directive
与 *ngIf
相反。
这是我的代码:
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
应该显示。
但是我有下一个错误:
Unhandled Promise rejection: Template parse errors: Can't bind to 'dirUnless' since it isn't a known property of 'div'. ("
有两种选择:
1) 将 @Input
名称从 unless
更改为 dirUnless
@Input() set dirUnless(condition: boolean) {
2) 使用别名
@Input('dirUnless') set unless(condition: boolean) {
问题是我没有在 NgModule 上声明我的指令