【问题标题】:component lifecycle in ionic离子中的组件生命周期
【发布时间】:2018-01-07 19:18:21
【问题描述】:

我已经构建了一个组件如下

export class AcknowledgementComponent implements AfterViewInit {

  private description: string;

  @Input('period') period: string;
  constructor() {
  }

  ngAfterViewInit() {
    console.log(this.period)
  }

在模板中使用它之前,我必须对该变量执行一些逻辑。但是在ngOnInitngAfterViewInit 中,变量是未定义的。有人可以建议使用哪个钩子来获取变量吗?

【问题讨论】:

  • 你在哪里设置这个组件?你能添加那个html吗?
  • 这是我在另一个模板中使用组件的方式。
  • period 是父组件中的变量对吧?
  • @Duannx 这是一个自定义组件,不是离子页面。
  • 您找到解决问题的方法了吗?

标签: angular typescript ionic2 ionic3


【解决方案1】:

你可以通过两种方式拦截输入属性:

Using a setter:

export class AcknowledgementComponent {
    private _period = "";

    @Input('period')
    set period(period:string) {
        this._period = (period && period.toUpperCase()) || 'No input';
    }
    // Works with async operations. Emample:
    // set period(period:string) {
    //     setTimeout(() => {
    //         this._period = (period && period.toUpperCase()) || 'No input';
    //     }, 5000);
    // }

    get period():string { return this._period; }
}

Using ngOnChanges:

import { Component, Input, SimpleChanges } from '@angular/core';
...
export class AcknowledgementComponent {
    @Input() period;

    ngOnChanges(changes: {[ propKey: string ]: SimpleChanges}){
        this.period = '';

        for(let propName in changes) {
            let changedProp = changes[propName];
            let newValue:string = String(changedProp.currentValue);
            this.period = newValue.toUpperCase();

            // Works with async operations. Emample:
            // setTimeout(() => {
            //     this.period = (newValue && newValue.toUpperCase()) || 'No input';
            // }, 5000);
        }
    }
}

这些示例只是将输入 string 设为大写。

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 2019-02-25
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多