我一直在关注如何使用结构指令here的例子 - 但我想做的一件事就是传递一些数据来自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
指令的绑定部分。
此指令可以再接受任何输入吗?
修改
感谢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() {}
}
修改
可以找到工作的掠夺者here
答案 0 :(得分:3)
将其重命名为
@Input('delayFoo')
结构指令中的输入需要包含选择器。