2017-03-23 37 views
2

我期待创建一个PopoverService,然后用它来显示另一个组件的弹出窗口。我的问题是,如何从服务更新组件的视图?从服务更新组件视图?

最终,我希望能够在popover中注入一个组件,以显示我需要的点击元素旁边的任何数据。

感谢您提供任何帮助!

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:(应处理更新酥料饼成分)

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:(使用服务显示popover)

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> 

回答

0
服务

都用于从外部API获取数据或加载本地模拟数据。通过在组件本身中使用布尔变量,可以更好地管理组件中DOM元素的可见性。这是做这件事的角度。

@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>