【发布时间】:2018-01-10 02:02:24
【问题描述】:
我正在尝试创建一个服务来处理一些自定义浮动操作按钮。 我的目标是能够在组件的 HTML 中定义按钮,以及使用可注入服务动态添加、修改、更新和删除它们。
以下代码在直接使用地址栏导航到页面时有效。但是,当使用链接(使用 [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 );
}
}
直接导航到页面时,我可以看到#actions 元素。通过使用链接进行放大时,#actions 元素无处可见。
有没有更好、更可靠的方法来动态添加这些类型的按钮? 我需要按钮位于根组件(当前活动的路由)中,以便在导航 UI 时正确换出它们,以便我能够在每个组件的 HTML 中定义按钮。
【问题讨论】:
-
“它不起作用”没有解释问题是什么。
-
感谢您的快速回复。我添加了一些额外的信息;希望这会有所帮助。我对路由的工作原理没有很深入的了解,我认为这可能与此有关。很难解释,对此我深表歉意
标签: angular angular2-services angular-routing angular-components