1

编码方面的新手,所以我不知道它是哪种语言。我有一个包含函数的 component.ts 文件。在ngOnInit()中,我在Js中写了一部分代码的依赖原因。我试图在这个 js 块中访问在 ngOnInit() 之外编写的函数。

尝试使用 this.openDialog() 访问该函数,但这只是显示错误,说它未定义。

尝试通过创建组件的对象并尝试调用函数来在js中定义函数本身,

constructor(public dialog: MatDialog, private datePipe: DatePipe) {

  }
ngOnInit(){
var testVar = new testComponent(dia, date);
//dia, date are respective constructor params
}

很确定那不合适,但试过了。

组件.ts:

export class test implements OnInit{
openDialog(){
//this is mat angular dialog
}
ngOnInit(){

 document.addEventListener('DOMContentLoaded', function () {

// trying to call the above openDialog here. 
});
}

}

试图调用 document.addEventListener() 中的对话框;转换document.addEventListener();不是一种选择。如果我可以在里面调用那个对话框会有所帮助。

编辑 1 共享更多代码,以获取信息:

document.addEventListener('DOMContentLoaded', function () {
      var events = []

      var calendarEl = document.getElementById('calendar');

      var calendar = new Calendar(calendarEl, {
        eventLimit: true, // for all non-TimeGrid views
        views: {
          dayGridMonth: {
            eventLimit: 5 // adjust to 6 only for timeGridWeek/timeGridDay
          }
        },
        themeSystem: 'bootstrap',
        businessHours: {
          daysOfWeek: [1, 2, 3, 4, 5],
          startTime: '00:00',
          endTime: '24:00',
        },
        header: {
          left: 'prev,next',
          center: 'title',
          right: 'dayGridMonth,listView,timeGridWeek,timeGridDay'
        },
        plugins: [dayGridPlugin, interactionPlugin, listPlugin, bootstrapPlugin, timeGrigPlugin],
        eventOverlap: false,
        displayEventTime: false,
        eventClick: function (info) {
          this.curEvnt = info;
          console.log(this.curEvnt)
          this.openDialog(info.event);   //ERROR

        }
      });
    calendar.render();
});

打开对话框已定义并可在 onInit 中调用,但我试图实现上述代码错误:this.openDialog is not a function

4

1 回答 1

1

你可以从Lifecycle Hooks角度使用。通过调用其构造函数创建组件/指令后,Angularlifecycle hook在特定时刻按以下顺序调用方法:

ngOnChanges()
ngOnInit()
ngDoCheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
ngOnDestroy()

请参考角度文档:Lifecycle Hooks

class MyComponent implements AfterContentInit {
    openDialog(){
        //this is mat angular dialog
    }

    ngAfterContentInit() {
        this.openDialog()
    }
}
于 2019-08-21T05:36:10.010 回答