Angular ChangeDetectionStrategy.OnPush未在输入更改时触发

时间:2017-06-04 16:41:47

标签: angular angular2-changedetection

我有一个简单的组件

@Component({
    selector: 'app-person-table',
    templateUrl: './person-table.component.html',
    styleUrls: ['./person-table.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class PersonTableComponent implements OnInit, OnDestroy {

    @Input() result: PageResult<Person>;

    public personsSub: Subscription;

    constructor(public personsStore: PersonsStore, public routerStore: RouterStore, public stringService: StringService) {
        this.personsSub = this.personsStore.getResult().subscribe(result => {
            this.result = result;
        });
    }

    ngOnInit() {
    }

    ngOnDestroy() {
        this.personsSub.unsubscribe();
    }

    goToPerson(person: Person) {
        if (person) {
            this.routerStore.go(['persons', person.id]);
        }
    }
}

然后在我的模板中,我只是做

<div class="table" *ngIf="result?.data && result.data.length > 0">
    <div class="row header">
        Header
    </div>
    <div class="row filters">
        Filter
    </div>
    <ng-template ngFor let-row [ngForOf]="result.data" let-i="index">
        <div class="row data" >
            Row #{{ i }}
        </div>
    </ng-template>
</div>

首先结果是null,但它会收到一个真正的PageResult对象。如果我注释掉changeDetection: ChangeDetectionStrategy.OnPush,则模板呈现正常。如果我让changeDetection: ChangeDetectionStrategy.OnPush处于活动状态,则模板为空白。

有人可以向我解释为什么更改result变量不会触发更改检测机制吗?

0 个答案:

没有答案