【发布时间】:2018-05-11 03:50:04
【问题描述】:
我是 Angular 2 的新手(请善待),我在尝试在按钮组件上使用的指令时遇到了困难。我需要做的是让指令执行 DOM 操作,以根据指令中捕获的输入状态切换组件内显示的内容。请参阅下面的 HTML:
<button ion-button actionIndicator [when]="isLoading">
<ion-icon [name]="userIcon"></ion-icon>
Update User
</button>
button 是一个组件,actionIndicator 是输入为when 的指令。按钮内内容的显示应根据actionIndicator 指令的when 状态进行切换。
指令代码:
@Directive({
selector: "[actionIndicator]"
})
export class ActionIndicatorDirective implements AfterViewInit {
constructor(
private el: ElementRef,
private viewContainer: ViewContainerRef,
private renderer: Renderer2
) {}
@Input() public actionIndicator;
@Input("when") set showIndicator(hasIndicator: boolean) {
if (hasIndicator) {
// hide current content (ion-icon & "Update User" text)
// create & display component <ion-spinner class="action-spinner"></ion-spinner)
}
else {
// remove component <ion-spinner>
// display content (ion-icon & "Update User" text)
}
}
ngAfterViewInit() {
// store reference to current component's content (ion-icon & "Update User" text) to be able to toggle based on state of [when]
}
}
我熟悉如何使用 DOM 脚本来显示/隐藏内容,但我相信 Angular 2 希望开发人员利用他们的抽象(ElementRef、ViewContainerRef 等)来处理 DOM 操作。有人可以了解一下这是如何工作的,尤其是对于指令;它必须是指令。
编辑解释(re: using *ngIf)
我意识到我应该更具体一些,因为人们在评论时只需做一个简单的*ngIf,我不能简单地这样做,因为我们的应用程序中大约有 40 个不同的地方需要这个,而且不仅仅是显示/隐藏文本,隐藏按钮文本时还需要显示微调器。当[when] 为true 时,我需要在按钮内显示<ion-spinner class="action-spinner"></ion-spinner>,然后在为false 时将其与按钮文本交换。您可以使用*ngIf 来适应这一点,但是每个地方都会很混乱,并且使用我上面概述的原始 HTML 会简单得多。 :)
非常感谢任何帮助!
【问题讨论】:
-
你为什么不直接使用 *ngIf。你做的比现在更难:
ng-container *ngIf="!isLoading"><ion-icon [name]="userIcon"></ion-icon> Update User</ng-container><ion-spinner *ngIf="isLoading"></ion-spinner> -
@JBNizet 请看我上面的解释,为什么我觉得
*ngIf不是最干净的解决方案。
标签: angular angular2-directives