莫代尔不反映绑定?

时间:2017-07-25 16:37:45

标签: angular ngx-bootstrap

我使用ngx-bootstrap在我的Angular4应用中打开一个模态:http://valor-software.com/ngx-bootstrap/#/modals#service-component

问题是模型没有反映模态的观点。对象已更新,但未在视图上反映出来。以下是重点:

showFromComponent(modalComponent: any, model?: any): void {
    let modal = this.modalService.show(modalComponent);

    if (model) {
        let component = <BaseModalComponent>modal.content;

        component.model = model;
        component.afterModelLoad();
    }
}

BaseModalComponent

import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';

export abstract class BaseModalComponent {
    model: any = {};

    protected constructor(
        public bsModalRef: BsModalRef
    ) { }

    public abstract afterModelLoad(): void;
}

ModalComponent

import { Component, OnInit } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';
import { BaseModalComponent } from '../../../app.core/abstractions/base-modal.component';

@Component({
    selector: 'visit-detail-modal',
    templateUrl: './visit-detail-modal.component.html',
    styleUrls: ['./visit-detail-modal.component.css']
})
export class VisitDetailModalComponent extends BaseModalComponent implements OnInit {
    description: string = '';

    constructor(
        public bsModalRef: BsModalRef
    ) {
        super(bsModalRef);
    }

    ngOnInit(): void {
    }

    afterModelLoad(): void {
        this.description = this.model.title;
    }
}

最后是观点:

<div class="modal-body">
    {{description}}
</div>

描述始终为空白。如果我在afterModelLoad中添加了调试器,则description已设置,但它不会更新视图。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在你的组件中注入私有cd:ChangeDetectorRef并在afterModelLoad方法结束时运行detectChanges:

afterModelLoad(): void {
    this.description = this.model.title;
    this.cd.detectChanges();
}

但是show方法BsModalService提供了一种传递数据来初始化组件的方法会更好。 这里报告了一些相同的问题/功能请求:https://github.com/valor-software/ngx-bootstrap/issues/2251。 关于类似的事情的讨论也发生在ng-bootstrap: https://github.com/ng-bootstrap/ng-bootstrap/issues/861