gpt4 book ai didi

angular - 是否可以在多个地方显示 Angular 组件的单个实例?

转载 作者:太空狗 更新时间:2023-10-29 17:19:39 25 4
gpt4 key购买 nike

假设我有这样的 html:

      <div *ngIf="(isVisible | async)">
<app-mycomponent></app-mycomponent>
</div>
<div *ngIf="!(isVisible | async)">
<app-mycomponent></app-mycomponent>
</div>

带有一个切换 isVisible 的按钮。每次切换可见性时都会创建一个新的组件实例。

所以我的问题是:我能否更改实现以在切换可见性时使用相同的 AppMyComponent 实例。例如。通过有一个包装器组件动态添加 app-mycomponent 或其他东西。

编辑:我的真实情况非常复杂,尽管这个例子没有意义,但我非常感兴趣是否可以这样做。

EDIT2:这是 stackbliz这解决了我的问题。

最佳答案

此答案基于 stackblitz example在此 answer 中提供我问过一个类似的问题。

第 1 步:创建一个指令,您可以在任何需要可重用组件的地方使用该指令。

@Directive({
selector: "[reusable-outlet]",
})
export class ReusableDirective implements OnInit {
constructor(
private viewContainerRef: ViewContainerRef,
private reusableService: ReusableService
) {}

public ngOnInit(): void {
this.reusableService.attach(this.viewContainerRef);
}
}

第 2 步创建将负责的服务:

  • 动态创建将被重用的组件
  • 将该组件附加和分离到在步骤 ~1 中创建的指令的 View 容器。

注意:了解何时分离组件是基于路由器事件,但如果您需要在不更改导航的情况下更改组件所在的位置,则应该可以改为基于消息。

@Injectable()
export class ReusableService {
private componentRef: ComponentRef<ReusableComponent>;

private currentViewContainerRef: ViewContainerRef;

constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector,
private router: Router
) {
const componentFactory =
this.componentFactoryResolver.resolveComponentFactory(ReusableComponent);
this.componentRef = componentFactory.create(injector);

this.router.events.subscribe((event) => {
if (event instanceof NavigationStart && this.currentViewContainerRef) {
this.detach(this.currentViewContainerRef);
}
});
}

public attach(viewContainerRef: ViewContainerRef) {
this.currentViewContainerRef = viewContainerRef;
viewContainerRef.insert(this.componentRef.hostView);
}

public detach(viewContainerRef: ViewContainerRef) {
viewContainerRef.detach(
viewContainerRef.indexOf(this.componentRef.hostView)
);
}
}

关于angular - 是否可以在多个地方显示 Angular 组件的单个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com