gpt4 book ai didi

angular - 从服务更新组件 View ?

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:42 26 4
gpt4 key购买 nike

我希望创建一个 PopoverService,然后我将使用它来显示来自另一个组件的弹出窗口。我的问题是,如何从服务更新组件的 View ?

最终,我希望能够将一个组件注入(inject)到弹出窗口中,以在单击的元素旁边显示我需要的任何数据。

感谢您提供的任何帮助!

popover.component.ts:

import {Component, Input} from "@angular/core";

@Component({
selector: 'kt-popover',
templateUrl: './popover.component.html'
})
export class PopoverComponent {
@Input() visible: boolean;
}
<div class="popover-container" (click)="hide()" [ngStyle]="{'display': visible ? 'block' : 'none'}">
<template [ngTemplateOutlet]="content"></template>
</div>

popover.service.ts:(应该处理更新 popover 组件)

import {
Injectable, ComponentFactoryResolver
} from "@angular/core";
import {PopoverComponent} from "./popover.component";

@Injectable()
export class PopoverService {
constructor(
private popover: PopoverComponent,
private resolver: ComponentFactoryResolver
) {}

public show(element: any, component: any, componentInput: any, options: any): void {
this.popover.visible = true;
}
}

test.component.ts:(使用服务来显示弹出框)

import {Component} from "@angular/core";
import {PopoverService} from "../services/popover/popover.service";

@Component({
selector: 'test',
templateUrl: './test.component.html'
})
export class TestComponent {
constructor(private popoverService: PopoverService) {}

public onClick(event: any): void {
this.popoverService.show(event.target, 'TestPopoverComponent', null, null);
}
}
<div (click)="onClick($event)">show popover</div>

最佳答案

服务旨在从外部 API 获取数据或加载本地模拟数据。通过在组件本身中使用 bool 变量,可以更好地管理组件中 DOM 元素的可见性。这是执行此操作的 Angular 方法。

@Injectable()
export class PopoverService {

private popUpVisibility:false;
constructor(
private resolver: ComponentFactoryResolver
) {}

show()
{
this.popUpVisibility=true;
}

}

test.component.ts:(使用服务来显示弹出窗口)

import {Component} from "@angular/core";
import {PopoverService} from "../services/popover/popover.service";

@Component({
selector: 'test',
templateUrl: './test.component.html'
})
export class TestComponent {

popUpVisibility:false;
constructor(private popoverService: PopoverService) {}

onClick {
this.popUpVisibility= this.popoverService.show();
}
}

现在,在您的 HTML 中,只需根据 popUpVisibility 切换可见性即可。

<div class="popover-container" *ngIf="popUpVisibility"> 
</div>

关于angular - 从服务更新组件 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42981023/

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