问题描述
我创建了一个类似于ngFor
的自定义结构指令.当我尝试使用<template>
元素语法使用它时,模板内的绑定有效,但是当我使用*语法时,该绑定不起作用.
I have created a custom structural directive similar to ngFor
. When I try to use it using <template>
element syntax, the binding inside the template is working but when I use * syntax, the binding is not working.
<!-- working -->
<template edit [editOf]="values" let-val="val">
<table >
<span>This is using template syntax {{val}}</span>
</table>
</template>
<!-- not working -->
<table *edit="let val1 of values">
<span>This uses star syntax {{val1}}</span>
</table>
这是此问题的 plnkr链接.
我在做什么错了?
更新:我想,现在我了解发生了什么事. let-val
错误地设置为用于绑定的对象的属性val
,但是我需要整个对象.因此,不应在模板中为let-val
分配任何值,然后我必须更新上下文.$ implicit使用该对象作为viewRef中的绑定源.
Update:I think, now I understand what is going on. The let-val
is incorrectly set to a property val
of object used for binding but I need the whole object. So, the let-val
shouldn't be assigned with any value in the template and then I'll have to update the context.$implicit with the object used as binding source in the viewRef.
感谢@ robisim74
Thanks to @robisim74
推荐答案
尝试一下:
import { ChangeDetectorRef,
Directive,
Input,
DoCheck,
IterableDiffer,
IterableDiffers,
TemplateRef,
ViewContainerRef,
EmbeddedViewRef} from "@angular/core";
@Directive({
"selector":"[edit][editOf]"
})
export class EditableTableDirective implements DoCheck {
private collection:any;
private differ:IterableDiffer;
private viewMap:Map<any,EmbeddedViewRef> = new Map<any,EmbeddedViewRef>();
constructor(
private changeDetector:ChangeDetectorRef,
private differs:IterableDiffers,
private template:TemplateRef,
private viewContainer:ViewContainerRef){
}
@Input() set editOf(coll:any){
this.collection = coll;
if (coll && !this.differ) {
this.differ = this.differs.find(coll).create(this.changeDetector);
}
}
ngDoCheck() {
if (this.differ) {
const changes = this.differ.diff(this.collection);
if (changes) {
changes.forEachAddedItem((change) => {
const view = this.viewContainer.createEmbeddedView(this.template, change.item);
view.context.$implicit = change.item;
this.viewMap.set(change.item, view);
});
changes.forEachRemovedItem((change) => {
const view = this.viewMap.get(change.item);
const viewIndex = this.viewContainer.indexOf(view);
this.viewContainer.remove(viewIndex);
this.viewMap.delete(change.item);
});
}
}
}
}
然后更正模板:
<table *edit="let item of values">
<span>This uses star syntax {{item.val}}</span>
</table>
我关注了这篇文章: http ://teropa.info/blog/2016/03/06/writing-an-angular-2-template-directive.html
这篇关于使用模板输入变量的Angular 2自定义结构指令绑定无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!