3
我一直在如何使用結構指令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
指令的結合部分我沒想到這個錯誤。
本指令可以採取任何更多的投入?
編輯
感謝岡特回答問題的第一部分。但是,如果我在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() {}
}
編輯
一個工作plunker可以發現here
感謝甘特 - 它的工作!我會假設選擇器的前綴是爲了防止衝突?有關於此的更多信息? – Katana24
我希望能在https://angular.io/docs/ts/latest/guide/structural-directives.html中找到一些東西。我認爲最近在一個GitHub的問題中提到了這個要求被刪除(不確定)。我只記得自己碰到它,偶爾會看到它。 –
另外 - 如果我在card.componet中定義一個對象,如下所示:foo:Object = {bar:'some value'}並嘗試通過它將打印爲undefined - 爲什麼?我將編輯這個問題來詳細說明 – Katana24