I'm newer to Angular 2 (please be kind) and am having a difficult time with a Directive I'm trying to utilize on a button component. What I need to do is have the directive perform DOM manipulation to toggle what content within the component gets displayed based on input state that's captured in the directive. Please see the HTML below:
<button ion-button actionIndicator [when]="isLoading">
<ion-icon [name]="userIcon"></ion-icon>
Update User
</button>
button is a component and actionIndicator is the directive with an input of when. The display of the content within the button should be toggled based on the state of when for the actionIndicator directive.
Directive Code:
@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]
}
}
I'm familiar with how to do DOM Scripting to show/hide the content, but I believe Angular 2 wants developers to utilize their abstraction (ElementRef, ViewContainerRef, etc) to handle the DOM manipulation. Can someone please make some sense of how this works, especially for a directive; it must be a directive.
Edited explanation (re: using *ngIf)
I realize I should be more specific as people are commenting with just do a simple *ngIf, I can't simply do this because there are about 40 different places throughout our app we're needing this, and it's not just show/hide the text, it's also required to display a spinner when the button text is hidden. I need to display the <ion-spinner class="action-spinner"></ion-spinner> within the button when [when] is true, and then swap that out with the button text when it's false. You could do *ngIf to accommodate this, but it'd be a mess in each spot, and would be much simpler with the original HTML I outlined above. :)
Any help is much appreciated!
ng-container *ngIf="!isLoading"><ion-icon [name]="userIcon"></ion-icon> Update User</ng-container><ion-spinner *ngIf="isLoading"></ion-spinner>- JB Nizet*ngIfwould be the cleanest solution. - Tom Doe