[英]How to access the value of a variable from a module to my component in angular 2?
So this is my app.module.ts
(i've injected NgxTypeaheadModule
like this) 所以这是我的
app.module.ts
(我已经注入了NgxTypeaheadModule
)
import { NgxTypeaheadModule } from '../components/common/components/ngx-typeahead/ngx-typeahead'
imports: [NgxTypeaheadModule]
This is the module ( ngxTypeahead.component.ts
) 这是模块(
ngxTypeahead.component.ts
)
This is ngxTypeahead.component.ts file inside the above module
这是上述模块内的ngxTypeahead.component.ts文件
export class NgxTypeAheadComponent implements OnInit, OnDestroy {
showSuggestions = false;
somefunc(){
showSuggestions = true;
}
}
In the above module component file, showSuggestions variable
will change according to user click. 在上述模块组件文件中,
showSuggestions variable
将根据用户单击而更改。
I'm using the above module in my component file below(
chat.component.ts
)我在下面的组件文件中使用上述模块(
chat.component.ts
)
export class ChatComponent implements OnInit, OnDestroy {
@ViewChild("input") input: ElementRef;
onKey(event) {
if (userInput.length == 0)) {
this.input.showSuggestions = false;
}
}
}
This is my chatComponent.html file 这是我的chatComponent.html文件
<input #input [(ngModel)]="inputText" ngxTypeahead (keyup)="onKey($event)">
But if i use this.input.showSuggestions
, i'm getting the value ,but i'm getting this error 但是,如果我使用
this.input.showSuggestions
,我得到的价值,但我得到这个错误
So Which is the correct way to pass the showSuggestions value from module to my chat.component.ts
?? 那么将showSuggestions值从模块传递到我的
chat.component.ts
的正确方法是?
Any suggestions or solution would be appreciated!! 任何建议或解决方案将不胜感激!
You could @ViewChild("input") input: NgxTypeAheadComponent;
您可以
@ViewChild("input") input: NgxTypeAheadComponent;
and get the component instance instead of the element ref, but that's bad practice and a path to violating unidirectional data flow! 并获取组件实例而不是元素ref,但这是一种不好的做法,并且是违反单向数据流的路径! Can also break change detection, doesn't work with OnPush.
还可以中断更改检测,不适用于OnPush。
Use @Input instead: @Input() showSuggestions = false;
改用@Input:
@Input() showSuggestions = false;
and in ChatComponent: 并在ChatComponent中:
<input #input [(ngModel)]="inputText" ngxTypeahead
(keyup)="onKey($event)" [showSuggestions]="showSuggestions">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.