Angular 4 中刷新页面和使用 routerLink 导航时的行为不同



我正在尝试创建一个处理一些自定义浮动操作按钮的服务。 我的目标是能够在组件的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 中定义按钮。

你可能真的不想这样做。

我不确定我是否掌握了您的要求。 我能想到动态插入按钮的唯一原因是,如果您允许用户定义按钮,这似乎不太可能,如果您允许他们将 javascript 代码插入 onclick,则可能是非常糟糕的做法。

你有一组有限的按钮吗? 为什么不创建一个包含所有按钮的组件,然后使用 *ngIf 来确定它们是否实际呈现?

以这种方式创建按钮和div 是一个非常非常糟糕的主意,你不能像现在这样修改 DOM。

但你应该这样做:

  • 定义按钮组件类
  • 将其定义为条目组件 app.module.ts 文件

  • 然后要动态创建一些组件,请使用下一个代码:

    let factory = this.componentFactoryResolver.resolveComponentFactory(ButtonComponent(; this.componentRef = this.other.createComponent(factory(;

看看这个链接 : 如何在容器中放置动态组件

最新更新