我一直在关注如何使用结构指令的示例here https://angular-2-training-book.rangle.io/handout/advanced-angular/directives/providing_context_variables_to_directives.html- 但我想做的一件事是从card.component
类进入delay.directive.ts
。我该怎么做呢?
export class DelayContext {
/**
- Line below demonstrated passing into an array of functions that can be called in the HTML
*/
// constructor(private loadTime: number, private myFunc: Array<Function>) {}
constructor(private loadTime: number, private delayService: DelayService) {}
}
@Directive({ selector: '[delay]'})
export class DelayDirective {
constructor(
private templateRef: TemplateRef<DelayContext>,
private viewContainerRef: ViewContainerRef
) { }
@Input('delay')
set delayTime(time: number) {
setTimeout(
() => {
let embedView = this.viewContainerRef.createEmbeddedView(
this.templateRef,
// new DelayContext(performance.now(),[this.foo,this.bar])
new DelayContext(performance.now(), new DelayService())
);
console.log(embedView);
},
time);
}
}
我尝试定义另一个输入参数,如下所示:
@Input('foo')
set fooParameter(parameters) {
console.log(parameters);
}
然后尝试用几种不同的方式在 HTML 中传递数据,但没有一种有效。这是我尝试过的:
<card *delay="500 * item; let loaded = loadTime; foo: 'test'">
<div class="main">
<button>{{item}}</button>
</div>
<div class="sub">{{loaded | number:'1.4-4'}}</div>
</card>
这会引发错误 -Can't bind to 'delayFoo' since it isn't a known property of 'card'
我没想到会出现这个错误,因为我们处于delay
指示。
该指令可以接受更多输入吗?
EDIT
感谢 Gunter 回答问题的第一部分。但是如果我在中定义一个对象card.component.ts
像这样:
bar: Object = {
val: 'Some Value'
};
然后尝试将其传递给指令:
<card *delay="500 * item; let loaded = loadTime; foo: bar">
这总是打印undefined
:
@Input('delayFoo')
set setFoo(obj) {
console.log(obj)
}
我们是否超出了卡片的范围?另外 - 完整的卡片组件:
import { Component } from '@angular/core';
import { DelayService } from './delay.service';
@Component({
selector: 'card',
template: `
<ng-content select=".main"></ng-content>
<ng-content select=".sub"></ng-content>`,
styles: [
`
:host {
display: inline-block;
font-family: 'Helvetica', sans-serif;
font-weight: 300;
margin: 1rem;
animation: fade-in 2s;
}
:host >>> .main {
padding: 2rem;
background: #e3f2fd;
font-size: 2rem;
text-align: center;
}
:host >>> .sub {
padding: 0.4rem;
background: #ef5350;
}
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
/* Firefox < 16 */
@-moz-keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
`
]
})
export class CardComponent {
bar: Object = {
val: 'Some Value'
};
ngOnInit() {}
}
EDIT
可以找到一个正在工作的笨蛋here https://plnkr.co/edit/Tny3nJ9mDFI9hPIBNd35?p=preview