如何在 angular 2 中将变量的值从模块访问到我的组件?

How to access the value of a variable from a module to my component in angular 2?

所以这是我的 app.module.ts(我已经像这样注入 NgxTypeaheadModule

   import { NgxTypeaheadModule } from '../components/common/components/ngx-typeahead/ngx-typeahead'    
   imports: [NgxTypeaheadModule]

这是模块 (ngxTypeahead.component.ts)

This is ngxTypeahead.component.ts file inside the above module

export class NgxTypeAheadComponent implements OnInit, OnDestroy {
      showSuggestions = false;

      somefunc(){
       showSuggestions = true;
   }

}

在上面的模块组件文件中,showSuggestions variable会随着用户的点击而变化


I'm using the above module in my component file below( chat.component.ts)

 export class ChatComponent implements OnInit, OnDestroy {
       @ViewChild("input") input: ElementRef;

       onKey(event) {
            if (userInput.length == 0)) {

                this.input.showSuggestions = false;
            }
        }
    }

这是我的 chatComponent.html 文件

 <input #input [(ngModel)]="inputText" ngxTypeahead (keyup)="onKey($event)">

但是如果我使用 this.input.showSuggestions,我得到了值,但是我收到了这个错误

那么,将 showSuggestions 值从模块传递到我的 chat.component.ts 的正确方法是什么??

如有任何建议或解决方案,我们将不胜感激!

您可以 @ViewChild("input") input: NgxTypeAheadComponent; 并获取组件实例而不是元素引用,但这是一种不好的做法,也是违反单向数据流的途径!也可以中断更改检测,不适用于 OnPush。

改用@Input:@Input() showSuggestions = false;,在 ChatComponent 中:

<input #input [(ngModel)]="inputText" ngxTypeahead 
(keyup)="onKey($event)" [showSuggestions]="showSuggestions">