【问题标题】:@Input not working in ionic 3 custom component from a lazy loaded page@Input 在延迟加载页面的 ionic 3 自定义组件中不起作用
【发布时间】:2018-11-30 13:36:03
【问题描述】:

我想将 titleKey 参数传递给自定义模块 navbar,该模块在延迟加载页面的 components.module.ts 中隔离。

components.module.ts

@NgModule({
    declarations: [NavbarComponent],
    imports: [
      IonicModule,
      CommonModule],
    exports: [NavbarComponent],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

navbar.component.ts

@Component({
  selector: 'navbar',
  templateUrl: 'navbar.html',
  inputs: ['titleKey']
})
export class NavbarComponent {
  @Input() titleKey:string;


  constructor(private navCtrl:NavController) {
  }
}

当我在延迟加载页面中使用此 navbar 时,输入不起作用

home.html

<ion-header>
    <navbar titleKey="my custom title"></navbar>
</ion-header>

<ion-content>
    .....
</ion-content>

如果我在navbar.component.ts 中打印@Input() titleKey:string 的结果,它是未定义的。

我已经尝试以其他形式调用此导航栏,但它似乎不起作用。

<ion-header>
    <navbar [titleKey]="my custom title"></navbar>
</ion-header>

and

<ion-header>
    <navbar [titleKey]="'my custom title'"></navbar>
</ion-header>

【问题讨论】:

  • 如果你在组件装饰器的inputs 属性中声明你的输入,我认为你不应该在你的类成员声明中装饰它们。因此,请尝试删除组件装饰器中的 inputs 属性,或者在声明之前删除装饰器 @Input()
  • 不确定是否已解决,但请尝试使用@Input() public titleKey: string;。然后,在ngOnInit 中,执行:console.log(this.titleKey);。还有,你为什么用inputs
  • 在 ngInit 中保留 console.log(this.titleKey) 并检查。不在构造函数中
  • @Florian 我要试试

标签: javascript angular ionic3


【解决方案1】:

我在延迟加载的 Web 组件方面遇到了类似的问题。好像@Input 是在组件初始化后设置的,不会触发更新。

为了解决这个问题,对于延迟加载的组件,我使用 getter 和 setter 进行输入和触发初始化逻辑。您可能还想检查您是否在同一个区域,如果不是,您可能需要注入 NgZone 并使用 zone.run() 来触发更新

private _titleKey: string;

@Input()
set titleKey(value: string) { this._titleKey = value; this.ngOnInit(); }
get titleKey(): string { return this._titleKey; }

【讨论】:

  • 您是否尝试过触发变更检测? @input() 装饰变量应在每次更改检测运行时更新
猜你喜欢
  • 2018-03-19
  • 2018-08-23
  • 2017-11-27
  • 1970-01-01
  • 2017-11-20
  • 1970-01-01
  • 2017-09-19
  • 1970-01-01
  • 2018-08-04
相关资源
最近更新 更多