Angular,如何使用基于布尔值的指令
Angular, how to use directive based on an boolean
我用一个ngFor
来表示不同的button
。我需要在不同的按钮上使用指令,但不是全部。
所以我写了这段代码:
<div *ngFor="let btn of btns">
<button {{ btn.useDirective ? 'appMyDirective' : '' }} ></button>
</div>
但是我得到这个错误
Error: Template parse errors:
Unexpected closing tag "button". It may happen when the tag has already been closed by another tag.
您的语法无效。要实现您想要的效果,请执行以下操作:
<div *ngFor="let btn of btns">
<button *ngIf="btn.useDirective" appMyDirective></button>
<button *ngIf="!btn.useDirective"></button>
</div>
尝试使用下面的方法。
<div *ngFor="let btn of btns">
<button appMyDirective *ngIf="btn.useDirective"></button>
<button *ngIf="!btn.useDirective"></button>
</div>
将你的指令更新为基于状态触发,例如考虑这个
@Directive({
selector: '[appHello]'
})
export class HelloDirective {
@Input() appHello:boolean;
constructor(private elem: ElementRef, private renderer: Renderer2) { }
ngAfterViewInit() {
if (this.appHello !== false ) {
this.renderer.setProperty(this.elem.nativeElement, 'innerHTML', 'Hi ');
}
}
}
模板
<div *ngFor="let btn of btns">
<button [appHello]="btn.useDirective">Hi </button>
</div>
如果您将值设置为 true,指令将起作用,否则什么也不会发生
我用一个ngFor
来表示不同的button
。我需要在不同的按钮上使用指令,但不是全部。
所以我写了这段代码:
<div *ngFor="let btn of btns">
<button {{ btn.useDirective ? 'appMyDirective' : '' }} ></button>
</div>
但是我得到这个错误
Error: Template parse errors: Unexpected closing tag "button". It may happen when the tag has already been closed by another tag.
您的语法无效。要实现您想要的效果,请执行以下操作:
<div *ngFor="let btn of btns">
<button *ngIf="btn.useDirective" appMyDirective></button>
<button *ngIf="!btn.useDirective"></button>
</div>
尝试使用下面的方法。
<div *ngFor="let btn of btns">
<button appMyDirective *ngIf="btn.useDirective"></button>
<button *ngIf="!btn.useDirective"></button>
</div>
将你的指令更新为基于状态触发,例如考虑这个
@Directive({
selector: '[appHello]'
})
export class HelloDirective {
@Input() appHello:boolean;
constructor(private elem: ElementRef, private renderer: Renderer2) { }
ngAfterViewInit() {
if (this.appHello !== false ) {
this.renderer.setProperty(this.elem.nativeElement, 'innerHTML', 'Hi ');
}
}
}
模板
<div *ngFor="let btn of btns">
<button [appHello]="btn.useDirective">Hi </button>
</div>
如果您将值设置为 true,指令将起作用,否则什么也不会发生