understanding the life cycle of components in Ionic

I created a component with the following structure:

export class AcknowledgementComponent implements AfterViewInit {

  private description: string;

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

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

Before using the variable in the template, I need to perform some logic. However, the variable is undefined in both ngOnInit and ngAfterViewInit. Can anyone suggest which lifecycle hook should be used to access the variable?

Answer №1

There are two ways to intercept the input property:

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);
        }
    }
}

Both examples transform the input string to uppercase.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The directive within the module was not carried out

After setting up a fresh module in my Angular 8 project and adding a new directive to it, nothing seemed to happen at runtime (although the compilation was successful). I even added console logs to the directive to check if it was being executed different ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

Ways to send JWT in the request header to an Angular6 application

Managing users and sessions through an external application such as a Web Application Firewall (WAF) The external app sends a JWT with user information in the request header to the Angular6 app The Angular6 app needs to extract the information from the req ...

The specified property is not recognized by the type in TypeScript

I have set up a basic form with validation in Ionic 2. The form functioned properly when I used 'ionic serve' but encountered issues when running 'ionic run'. My suspicion is that the problem lies within my TypeScript code, specifically ...

Access a PDF document in a new tab and save it with a specific file name using Angular

I am facing a challenge in Angular where I want to open a PDF file in a new tab and enable the user to download it with a specific name (Example.pdf). The current code successfully downloads the PDF but does not open a new tab (target=_blank is ineffecti ...

The attribute 'randomUUID' is not found within the 'Crypto' interface

I attempted to utilize the crypto.randomUUID function in my Angular app version 13.1, however, it does not seem to be accessible. When trying to use it, I encountered this error: TS2339: Property 'randomUUID' does not exist on type 'Crypto ...

The Angular application is receiving a 404 error when trying to access the .NET Core

Having trouble calling a method in the controller via URL, as I keep encountering a 404 error. What could be the issue? API Endpoint: http://localhost:5000/Home/HomeTest /*.net core web-api*/ namespace MyApp.Controllers { Route("api/[controller]") ...

Is there a method to implement retries for inconsistent tests with jest-puppeteer?

Currently, I am struggling with an issue where there is no built-in method to retry flaky tests in Jest. My tech stack includes Jest + TypeScript + Puppeteer. Has anyone else encountered this problem or have any suggestions for possible solutions? I attem ...

Is there a method in Angular to restrict change detection to only the current component and its descendant components?

Is there a way to trigger an event in the child component without traversing the entire component tree from the parent? import { Component } from '@angular/core' @Component({ selector: 'my-app', template: '<b>{{ te ...

Is it possible to utilize an array of numbers as a data source in ng2-smart table?

Hey there, I'm currently facing an issue with populating ng2-smart-table with an array of numbers. When I try to display the table, all I see is 6 empty rows like this: https://i.stack.imgur.com/DZJjq.png Here's the code for the table: <ng2- ...

I'm having an issue with my ng2-charts where data label values are not displaying in the graphs

I'm currently working on an Angular project that utilizes ng2-charts and chart.js. Interestingly, when I run the project locally, the datalabels are visible (check: project run locally). However, once I deploy the project onto a server, the datalabels ...

Enhancing TypeScript type definitions for the Response.render() method in Express

Struggling with enhancing the type safety of my Express project by extending the Response.render function. import { Response } from "express"; import { Product } from "../models/Product.interface"; export interface ProductListResponse ...

Using RXJS with the 'never' subject as the specified generic type

In my current Angular project, I am using RXJS and Typescript. The code snippet below shows what I have implemented: const sub = new Subject<never>(); My understanding is that the above line implies that any subscriber defining the 'next' ...

NextJS Typescript Layout is throwing errors due to the absence of required props

After following the instructions on https://nextjs.org/docs/basic-features/layouts#with-typescript and making changes to my Home page as well as _app.tsx, I encountered an issue with the layout file Layout.tsx. The provided guide did not include an exampl ...

Guide to simulating a function using .then within a hook

I am using a function that is called from a hook within my component. Here is my component: ... const handleCompleteContent = (contentId: string) => { postCompleteContent(contentId, playerId).then(data => { if (data === 201) { ... The caller ...

“What is the process of setting a referenced object to null?”

Here is an example of the code I'm working with: ngOnInit{ let p1 : Person = {}; console.log(p1); //Object { } this.setNull<Person>(p1); console.log(p1); //Object { } } private setNull<T>(obj : T){ obj = null; } My objective is to ...

Ways to resolve the Ionic v1 deprecation error problem

I am facing a problem with an Ionic v1 deprecation error, causing it to not work properly. ionic build ios ionic emulate android The basic commands are failing to produce the desired outcome. Is there a way to resolve this issue? Note: My application is ...

Enhance the readability of your Angular/Ionic applications with proper hyphenation

In my Ionic 3 app, I am using an ion-grid. Some words do not fit within the columns and are cut off, continuing on the next row without any hyphens added for proper grammar context. See image https://i.stack.imgur.com/3Q9FX.png. This layout appears quite ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...