Javascript 无法从Angular 4中的viewChild元素调用函数

Javascript 无法从Angular 4中的viewChild元素调用函数,javascript,angular,viewchild,Javascript,Angular,Viewchild,我试图使用@ViewChild以编程方式触发单击事件,以调用名为open()的函数。我总是收到错误消息 无法读取未定义的属性“close” //组成部分 import {Component, OnInit, OnChanges, ViewChild, ElementRef} from '@angular/core'; export class CalendarComponent implements OnInit { // Material Design Float Button

我试图使用
@ViewChild
以编程方式触发单击事件,以调用名为open()的函数。我总是收到错误消息

无法读取未定义的属性“close”

//组成部分

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">

请使用nativeElement,如

this.floatButton.nativeElement.close();
HTML:



但是我看不到您在哪里调用减量方法。

您可以告诉ViewChild注释只使用component component而不是ElementRef,这将使您更容易理解您调用的组件

在HTML中,在id属性旁边使用类似于#float按钮的别名


如果它仍然告诉您close()方法不存在,可能是因为它尚未初始化,请在调用该方法之前检查初始化

谢谢,但是我试过了,我得到了下面的错误<代码>无法读取HTML中未定义的属性“nativeElement”添加#float按钮递减()方法只是html组件的一部分,如下所示:
chevron_left
您是否尝试在ngc float button标记中的html中添加#float button?谢谢是的#float button是它没有接受#float button-没有乐趣我会继续尝试thankshi@Rancio您能提供一个例子吗?检查它是否已初始化,类似的子类应该可以工作:
initialize=false//ngOnInit(){this.initialize=true;}
Parent:
@ViewChild('float-button')公共floatButton:NgcFloatButton;//somecode decrement():void{//如果(this.floatButton.initialize){this.floatButton.close();}}
<ngc-float-button
        id="float-button"
        #float-button
        icon="add"
        color="#c0392b"
        class="ngc-float-button-container ngc-float-button-main-button"
        (click)="ngcFloatButtonData.onToggle()"
        [direction]="ngcFloatButtonData.direction">