我目前正在尝试使用bootstrap创建动态弹出窗口,其中从模式的html模板,我动态添加标题,正文和页脚。但是当我的代码被执行时,在浏览器控制台中我会收到一些错误,因为从一开始就没有为页眉,正文和页脚定义任何值。
我是新手,我不习惯面向对象的编程。
这是我的代码: https://stackblitz.com/edit/ngx-bootstrap-fh92s3?file=app%2Fapp.module.ts
modal.service.ts
import {Injectable} from '@angular/core';
import {ModalModel} from './modal.model';
import {Subject} from "rxjs/Subject";
declare let $: any;
@Injectable()
export class ModalService {
modalData = new Subject<ModalModel>();
modalDataEvent = this.modalData.asObservable();
open(modalData: ModalModel) {
this.modalData.next(modalData);
$('#myModal').modal('show');
}
}
modal.component.ts
import { Component } from '@angular/core';
import { ModalService } from './modal.service';
import {ModalModel} from './modal.model';
declare let $: any;
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: [ './modal.component.css' ]
})
export class ModalComponent {
modalData: ModalModel;
constructor(private modalService: ModalService) {
this.modalService.modalDataEvent.subscribe((data) => {
this.modalData = data;
})
}
}
从任何组件调用此服务
import { Component } from '@angular/core';
import { ModalService } from '../modal/modal.service';
import { ModalModel } from '../modal/modal.model';
declare let $: any;
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: [ './home.component.css' ]
})
export class HomeComponent {
modelData = new ModalModel();
constructor(private modalService: ModalService) {
}
open() {
this.modelData.header = 'This is my dynamic HEADER from Home component';
this.modelData.body = 'This is my dynamic BODY from Home component';
this.modelData.footer = 'This is my dynamic footer from Home component';
this.modalService.open(this.modelData);
}
}
答案 0 :(得分:0)
这是因为'modalData'仅在调用subscribe
时分配,但模板绑定在此之前发生(因为组件从头开始包含),当modelData
仍未定义时。
您可以初始化yurzui建议的数据,也可以使用?
运算符,如果对象为null或未定义,则不会评估属性。
<h4 class="modal-title">{{modalData?.header}}</h4>
<div class="modal-body">
<p>{{modalData?.body}}</p>
</div>