[英]Angular, how to use directive based on an boolean
我使用ngFor
顯示不同的button
。 我需要在其他按鈕上使用指令,但不是全部。
所以我寫這段代碼:
<div *ngFor="let btn of btns">
<button {{ btn.useDirective ? 'appMyDirective' : '' }} ></button>
</div>
但是我得到這個錯誤
錯誤:模板解析錯誤:意外的結束標記“按鈕”。 當標簽已經被另一個標簽關閉時,可能會發生這種情況。
您的語法無效。 要歸檔所需的文件,請執行以下操作:
<div *ngFor="let btn of btns">
<button *ngIf="btn.useDirective" appMyDirective></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,則該指令將起作用,否則將不會發生任何事情
請嘗試使用下面的方法。
<div *ngFor="let btn of btns">
<button appMyDirective *ngIf="btn.useDirective"></button>
<button *ngIf="!btn.useDirective"></button>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.