Angular4在构造函数中调用一个函数

问题描述 投票:3回答:2

我试图在Angular 4的构造函数中调用一个模态函数,但是函数得到突出显示没有正确调用,当页面加载时,不会在日志中读取错误,并且模式不会弹出它的假设。屏幕变黑,但模态中的文字没有显示出来。

constructor(public formBuilder: FormBuilder,
            public router: Router,
            public toastr: ToastrService,
            public http: HttpClient,
            public modalService: BsModalService,) {
  if (this.getWardData) {
    this.displayHint();
  }
}

displayHint(template: TemplateRef<any>) {
  this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
}

HTML

<ng-template #template>
  <div class="modal-body text-center">
    <p>Do you want to Continue where you left?</p>
    <button type="button" class="btn btn-default" (click)="confirm()" >Yes</button>
    <button type="button" class="btn btn-primary" (click)="decline()" >No</button>
  </div>
</ng-template>
angular typescript constructor
2个回答
1
投票

尝试使用以下代码

constructor(public formBuilder: FormBuilder,
    public router: Router,
    public toastr: ToastrService,
    public http: HttpClient,
    public modalService: BsModalService, ) {
    // if (this.getWardData) {
    //   this.displayHint();
    // }
  }

  ngOnInit() {
    if (this.getWardData) {
      this.displayHint();
    }
  }

  displayHint(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, { class: 'modal-sm' });
  }

0
投票

我认为你有模态模板的问题。您可以运行模态,但需要传递给displayHint方法模板参数(TemplateRef)。在您查看中,我看到您有此模板,但您在组件实现中没有引用此模板。将这部分代码添加到组件中(参考模态模板 - 您需要这个以显示模态):

@ViewChild('template') private modalTemplate: TemplateRef<any>;

从你的构造函数中删除this.displayHint()(我在下面解释),在ngOnInit实现上添加ngAfterViewInit并在那里添加displayHint方法调用:

export class YourComponentName implements AfterViewInit {
    @ViewChild('template') private modalTemplate: TemplateRef<any>;

    getWardData = true; // for example purposes - always true

    constructor(public formBuilder: FormBuilder,
                public router: Router,
                public toastr: ToastrService,
                public http: HttpClient,
                public modalService: BsModalService
    ) {}

    ngAfterViewInit() {
        if (this.getWardData) {
            this.displayHint(this.modalTemplate);
        }
    }

    displayHint(template: TemplateRef<any>) {
      this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
    }
}

构造函数和组件的ngOnInit / ngAfterViewInit之间存在巨大差异。 Angular bootstrap过程包括两个主要阶段:

  • 构建组件树
  • 运行变化检测

您的控制器方法正在“构建组件树”阶段中运行

(这里未定义对模态模板的引用)

您的ngOnInit方法正在“运行更改检测”阶段中运行。

(此处定义了对模态模板的引用)

@Input通信机制作为以下更改检测阶段的一部分进行处理,因此输入绑定在构造函数中不可用。

所以你不能从构造函数运行你的模态

More about lifecycle hooks you can find here

Live working example you can find here

© www.soinside.com 2019 - 2024. All rights reserved.