I am attempting to create a service which handles some custom floating action buttons. My aim is to be able to either define the buttons in the HTML of a component, as well as, add, modify, update and delete them dynamically using an injectable service.
The following code works when navigating to the page directly using the address bar. It doesn't work, however, when navigating to the same page using links (with [routerLink]).
@Injectable()
export class ActionButtonService {
constructor( private element: ElementRef ) {
}
private container: HTMLElement;
private getContainer = function getContainer(){
if ( this.container == null ) {
let foundContainer = document.getElementById( "actions" );
if ( foundContainer != null ) {
this.container = foundContainer;
} else {
let createdContainer = document.createElement( "div");
createdContainer.setAttribute( "id", "actions" );
this.element.nativeElement.parentElement.appendChild( createdContainer );
this.container = createdContainer;
}
}
return this.container;
}
public addAction = function( icon: string, title: string, onclick, id: string = null ) {
let container = this.getContainer();
let newButton = document.createElement( "a" );
newButton.title = title;
if ( id != null ) newButton.id = id;
newButton.innerHTML = "<md-icon class=\"material-icons mat-icon\">"+ icon +"</md-icon>";
newButton.onclick = onclick;
container.appendChild( newButton );
}
}
When navigating directly to the page, I can see the #actions element. When magnifying through the use of links, the #actions element is nowhere to be seen.
Is there a better, more reliable way to go about adding these kinds of buttons dynamically? I'd need the buttons to be in the root component (currently active route), so that they get swapped out correctly when navigating the UI and so that I'm able to define the buttons within the HTML of each component.