【问题标题】:property undefined when setting a property when calling a template调用模板时设置属性时属性未定义
【发布时间】: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


【解决方案1】:

这是因为 'modalData' 仅在调用 subscribe 时才分配,但模板绑定在此之前发生(因为组件从一开始就包含在内),此时 modelData 仍未定义。

您可以像 yurzui 建议的那样初始化数据,也可以使用 ? 运算符,如果对象为 null 或未定义,它将不会评估属性。

  <h4 class="modal-title">{{modalData?.header}}</h4>

  <div class="modal-body">
    <p>{{modalData?.body}}</p>
  </div>

Edited stackblitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 2021-11-19
    相关资源
    最近更新 更多