从服务更新组件视图?

时间:2017-03-23 15:54:15

标签: angular typescript

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

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

感谢您提供任何帮助!

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

1 个答案:

答案 0 :(得分: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>