隐式变量的更改如何更新视图

时间:2019-11-07 01:02:56

标签: javascript angular

我正在读一本Angular的书,下面是一些代码:

//template.html
 <tr *paFor="let item of getProducts(); let i = index; let odd = odd;
    let even = even">

其中paFor是具有与ngFor相同功能的自定义指令的选择器,以下是该指令的代码

@Directive({
    selector: "[paForOf]"
})
export class PaIteratorDirective {

    private differ: DefaultIterableDiffer<any>;
    private views: Map<any, PaIteratorContext> = new Map<any, PaIteratorContext>();

    @Input("paForOf")
    dataSource: any;

    constructor(private container: ViewContainerRef,
        private template: TemplateRef<Object>,
        private differs: IterableDiffers,
        private changeDetector: ChangeDetectorRef) {
    }

    ngOnInit() {
        this.differ =
            <DefaultIterableDiffer<any>>this.differs.find(this.dataSource).create();
    }

    ngDoCheck() {
        let changes = this.differ.diff(this.dataSource);
        if (changes != null) {
            changes.forEachAddedItem(addition => {
                let context = new PaIteratorContext(addition.item,
                    addition.currentIndex, changes.length);
                context.view = this.container.createEmbeddedView(this.template,
                    context);
                this.views.set(addition.trackById, context);

            });
            let removals = false;
            changes.forEachRemovedItem(removal => {
                removals = true;
                let context = this.views.get(removal.trackById);
                if (context != null) {
                    this.container.remove(this.container.indexOf(context.view));
                    this.views.delete(removal.trackById);
                    //console.log(removal.trackById);
                }
            });
            if (removals) {
                let index = 0;
                this.views.forEach(context =>
                    context.setData(index++, this.views.size));
            }
        }
    }

class PaIteratorContext {
    odd: boolean;
    even: boolean;
    first: boolean;
    last: boolean;
    index: number;
    view: ViewRef;

    constructor(public $implicit: any,
        public position: number, total: number) {
        this.setData(position, total);
    }

    setData(index: number, total: number) {
        this.index = index;
        this.odd = index % 2 == 1;
        this.even = !this.odd;
        this.first = index == 0;
        this.last = index == total - 1;
    }
}

我的问题是,让我们说有两个项目:最初在我删除itemB之后,itemA和itemB,代码将上下文对象更新为:

// removals is true
if (removals) {
   let index = 0;
   this.views.forEach(context =>
   context.setData(index++, this.views.size));
}

,因此视图中现有itemA的所有上下文数据值将得到更新以反映最新更改。我明白了但这是否意味着当上下文数据更改时,Angular会销毁与itemA关联的当前视图并重新创建该视图?否则,上下文数据的改变会导致改变现有视图的机制是什么?

0 个答案:

没有答案