Angular4在构造函数中调用函数

时间:2019-02-19 16:25:38

标签: angular typescript constructor

我正在尝试在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>

2 个答案:

答案 0 :(得分: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' });
  }

答案 1 :(得分: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之间存在巨大差异。角引导过程包括两个主要阶段:

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

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

(此处未定义对模式模板的引用)

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

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

  

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

所以您不能从构造函数运行模式

More about lifecycle hooks you can find here

Live working example you can find here