[英]Using @Input decorator to pass data from outside the angular component
In an ionic app, i am using a angular component. 在离子应用程序中,我使用角度组件。 In that angular component, i have a variable
headerText
which in initialized from the page where this component is used. 在该角度组件中,我有一个变量
headerText
,它从使用该组件的页面初始化。
Problem is that headerText
variable is always undefined. 问题是
headerText
变量总是未定义的。
How can i fix this problem? 我该如何解决这个问题?
This is the angular component where headerText
variable is defined. 这是定义
headerText
变量的角度组件。
import { Component, Input, OnInit } from '@angular/core';
import { MenuController, NavController } from 'ionic-angular';
@Component({
selector: 'custom-header-text',
templateUrl: 'custom-header-text.html'
})
export class CustomHeaderTextComponent implements OnInit {
@Input() headerText: string;
constructor(private navCtrl : NavController,
private menuCtrl : MenuController) {
}
ngOnInit() {
setTimeout(() => {
console.log('text = ' + this.headerText);
}, 3000);
}
goBack() {
this.navCtrl.pop();
}
openMenuPage() {
this.menuCtrl.enable(true,'bl-menu')
this.menuCtrl.open();
}
}
This is how i am passing a value to this headerText
variable from where this component is used. 这是我如何将值传递给此
headerText
变量使用此组件的位置。
<custom-header-text [headerText]="'Inbox'"></custom-header-text>
See below. 见下文。
The reason why this is not working is that your root element in which you place the
<custom-header-text [headerText]="'Inbox'"></custom-header-text>
is not an angular component.这不起作用的原因是您放置
<custom-header-text [headerText]="'Inbox'"></custom-header-text>
的根元素不是角度组件。 Because of this, Angular won't compile this element.因此,Angular不会编译此元素。 And Angular does not read attribute values during runtime, only during compile time, as otherwise we would get a performance hit.
Angular不会在运行时读取属性值,只是在编译期间,否则我们会受到性能影响。
Answered here 这里回答
Angular 2 input parameters on root directive 根指令上的Angular 2输入参数
Your code wasn't working as the HeaderModule was not correctly configured. 您的代码无法正常工作,因为未正确配置HeaderModule。
There were a few issues with your implementation: 您的实施存在一些问题:
After fixing those, it was working as expected. 修好后,它按预期工作。 Here's an Updated StackBlitz for your ref.
这是你的ref的更新StackBlitz 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.