【发布时间】:2019-03-17 17:05:36
【问题描述】:
我正在构建一个指令,该指令应替换组件(加载器)包含的元素,并在达到延迟时发送错误消息。
遇到的问题:列表中的所有元素都被加载器替换,而不是我点击的那个。
我找不到只选择被点击的元素的方法。
Stackblitz: https://stackblitz.com/edit/angular-wmybgc?file=src%2Fapp%2Floader-and-error-handler.directive.ts
指令:
import { StoreService } from '@services/store/store.service';
import { Directive, Input, ViewContainerRef, TemplateRef, ComponentFactoryResolver, Type } from '@angular/core';
import { LoaderComponent } from '@components-ui/loader/loader.component';
export class LoaderAndErrorContext {
$implicit: boolean;
message: string;
}
@Directive({
selector: '[loaderAndErrorHandler]'
})
export class LoaderAndErrorHandlerDirective {
private isLoading: boolean;
@Input('loaderAndErrorHandlerWait') private delay: number;
@Input('loaderAndErrorHandlerBeforeDisplaying') private message: string;
@Input() set loaderAndErrorHandler(isLoading: boolean) {
this.isLoading = isLoading;
this.viewControllerRef.clear();
if (this.isLoading) {
this.displayComponent(LoaderComponent);
setTimeout(() => {
this.store.sendNotification(this.message);
}, this.delay);
}
else {
this.viewControllerRef.clear();
this.viewControllerRef.createEmbeddedView(this.templateRef);
}
}
constructor(
private viewControllerRef: ViewContainerRef,
private templateRef: TemplateRef<any>,
private componentFactoryResolver: ComponentFactoryResolver,
private store: StoreService
) {
this.displayComponent = this.displayComponent.bind(this);
}
displayComponent = (component: Type<LoaderComponent>, message?: string): void => {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
message
? this.viewControllerRef.createComponent(componentFactory).instance['message'] = message
: this.viewControllerRef.createComponent(componentFactory);
}
}
实施:
<h2>Mes documents</h2>
<ul [@fadeInOutStagger]="documents.length">
<ng-container *loaderAndErrorHandler="isLoading; wait 2000 beforeDisplaying errorMessage;">
<li *ngFor="let document of documents | sortBy:'label'">
<article (click)="getDocument(document.id)" class="document-label">
<input type="image" src="assets/images/icon/icone_document.svg">
<label>
<strong>{{document.label}}</strong>
</label>
</article>
<article class="document-date">
<p>{{document.date | dateTo:'JJ Mois'}}</p>
</article>
</li>
</ng-container>
</ul>
【问题讨论】:
-
你能为此创建一个堆栈闪电战吗?
-
@dince12 它应该可以工作stackblitz.com/edit/…
-
isLoading布尔值与每个项目共享,因此当您更改一个的值时,每个项目都会更改。
标签: angular angular2-directives