【发布时间】:2018-02-08 19:36:46
【问题描述】:
我正在使用vmware/clarity design system,我正在尝试使用动态组件加载outlined in angular.io 来实现动态应用级警报。我以前遵循过这种模式,但我似乎无法让它与来自 Clarity 的警报一起工作。
app.component.ts
import { AfterViewInit, Component, ComponentFactoryResolver, OnDestroy, ViewChild } from '@angular/core';
import { ClrAlert } from '@clr/angular';
import { AlertsHostDirective } from './directives/alerts-host.directive';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit, OnDestroy {
@ViewChild(AlertsHostDirective) alerts: AlertsHostDirective;
private interval: NodeJS.Timer;
constructor(private _componentFactoryResolver: ComponentFactoryResolver) { }
ngAfterViewInit(): void {
this.alert();
this.getAlerts();
}
ngOnDestroy(): void {
clearInterval(this.interval);
}
private alert() {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(ClrAlert);
const viewContainerRef = this.alerts.viewContainerRef;
const componentRef = viewContainerRef.createComponent(componentFactory);
componentRef.instance.isAppLevel = true;
componentRef.changeDetectorRef.detectChanges();
}
private getAlerts() {
this.interval = setInterval(() => {
this.alert();
}, 5000);
}
}
app.component.html
<clr-main-container>
<clr-alerts>
<ng-template appAlertsHost></ng-template>
<clr-alert clrAlertType="info"
[clrAlertAppLevel]="true">
<div class="alert-item">
<span class="alert-text">This is the first app level alert. </span>
<div class="alert-actions">
<button class="btn alert-action">Fix</button>
</div>
</div>
</clr-alert>
<clr-alert clrAlertType="danger"
[clrAlertAppLevel]="true">
<div class="alert-item">
<span class="alert-text">This is a second app level alert.</span>
<div class="alert-actions">
<button class="btn alert-action">Fix</button>
</div>
</div>
</clr-alert>
</clr-alerts>
...
alerts-host.directive.ts
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appAlertsHost]'
})
export class AlertsHostDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
如果我将指令放在 ClrAlerts 组件上,它的工作方式应该是在 DOM 中的 ClrAlerts 之后附加应用程序级别的警报。但我希望我的所有应用程序级警报在它们进入时出现在该组件中。反过来,我希望寻呼机组件似乎也已更新。
这可能吗?
【问题讨论】:
-
您实际上总是在创建
ClrAlert组件,这是如何动态的?在您的示例中,您可以只使用一个简单的*ngFor就可以了。 -
@Eudes ,也许有比动态更好的词,但我借用了动态组件加载器的 angular.io 文档中的措辞。正如您所说,使用它们概述的模式,您正在加载相同的组件,强类型。我认为动态的意思是“在运行时”。换句话说,当客户端已经加载了应用程序时,可以基于用户交互或其他事件创建组件。
*ngFor要求我在启动应用程序之前了解所有通知,这错过了我想要做的事情。 -
*ngFor 是动态的,你不需要在运行时知道所有的通知。如果您的应用程序中有一个全局提供程序来跟踪应显示的所有通知,并且用户交互和事件会更新该列表,那么 *ngFor 将非常适合您的用例。
-
确实如此。让我试一试...
标签: angular dynamic angular2-changedetection vmware-clarity clarity