我试图以编程方式触发click事件使用 @ViewChild
来调用一个名为open()的函数我总是得到错误
Cannot read property 'close' of undefined
// 零件
import {Component, OnInit, OnChanges, ViewChild, ElementRef} from '@angular/core';
export class CalendarComponent implements OnInit {
// Material Design Float Button
// https://github.com/GustavoCostaW/ngc-float-button
ngcFloatButtonData: Object = {
direction: 'up',
open:false,
onToggle: function(): void {
this.open = !this.open;
},
close: function(): void {
this.open = false;
}
};
public elementRef;
@ViewChild('float-button') public floatButton: ElementRef;
constructor(
public dialog: MatDialog,
public el: ElementRef,
) {
}
decrement(): void {
// try to call the function close()
this.floatButton.close();
}
} // end
//组件html
<ngc-float-button
id="float-button"
icon="add"
color="#c0392b"
class="ngc-float-button-container ngc-float-button-main-button"
(click)="ngcFloatButtonData.onToggle()"
[direction]="ngcFloatButtonData.direction">
2 回答
而不是this.floatButton.close()请使用nativeElement之类的
HTML:
但我无法看到你在哪里调用减量方法 .
您可以告诉ViewChild注释只使用组件ComponentWhatever而不是ElementRef,它将使您更容易理解您调用的组件 .
在HTML上使用除了id属性之外的别名#float-button .
如果它仍然告诉你close()方法不存在可能是因为它尚未初始化,请在调用方法之前检查初始化 .