【发布时间】:2018-05-13 04:23:11
【问题描述】:
我目前正在尝试使用引导程序创建一个动态弹出窗口,其中从模态的 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);
}
}
【问题讨论】:
-
用默认值初始化你的modalData,这样它就不会抛出错误stackblitz.com/edit/ngx-bootstrap-a7csh6?file=app/modal/…其他方法是保存
*ngIf的导航运算符有很多类似的问题,所以我会关闭它 -
@yurzui 谢谢!但你刚刚修改了modal.component.ts?在我的真实代码中,我避免了错误,但是当我点击按钮时,值不会改变。
-
为什么在 Angular 项目中使用 jquery?
-
是的.......为什么?
标签: angular