这是我上周发布的this question的后续内容,感谢Gunter到目前为止的帮助。我想要实现的目标是定义一个我可以在动态内容中使用的函数。这是我到目前为止所拥有的。使用home.component.html
和card.component
:
delay.directive
<div *ngFor="let item of [1,2,3,4,5,6]">
<template [delay]="500 * item" let-loaded="loadTime" let-events="events">
<card [subject]="events">
<div class="main">
<button (click)="btnOnClickTest()">{{item}}</button>
</div>
<div class="sub">{{loaded | number:'1.4-4'}}</div>
</card>
</template>
</div>
现在是delay.directive
import { Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
import { CardComponent } from './card.component';
import { Subject } from 'rxjs/Subject';
export class DelayContext {
public events: Subject<any> = new Subject();
constructor(private loadTime: number) {}
public btnOnClickTest() {
console.log('Testing....')
}
}
@Directive({ selector: '[delay]'})
export class DelayDirective {
constructor(
private templateRef: TemplateRef<DelayContext>,
private viewContainerRef: ViewContainerRef
) {}
public btnOnClickTest() {
console.log('Testing....')
}
@Input('delay')
set delayTime(obj) {
console.log('delay', obj);
setTimeout(
() => {
let context = new DelayContext(performance.now());
context.events.subscribe(e => console.log(`event`, obj, e));
let embedView = this.viewContainerRef.createEmbeddedView(this.templateRef, context);
console.log('embedView', embedView);
},
obj.time);
}
@Input('delayFoo')
set setFoo(obj) {
console.log('obj', obj)
}
}
上面你可以看到我定义了一个名为btnOnClickTest
的测试函数,我试图在插入动态内容的地方使用它。
现在我想,或许这不是接近这个的正确方法......
答案 0 :(得分:1)