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

Troubleshooting an issue with asynchronous reactive form validators in Angular

I encountered an issue where I need to access a service that sends an http request to an API to verify the existence of a given username. Snippet from Auth component: usernameCheck(username: string){ return this.http.get(this.baseUrl + "usernamecheck?u ...

The Angular-slickgrid is encountering an issue where it is unable to access the property "hostView" as it

Hey there developers, I've been experimenting with the angular slickgrid library and attempting to incorporate the rowDetailView feature it offers. The issue I'm facing is that while I can expand the view by clicking on it, I'm unable to c ...

Encountered an error with ng build --prod while attempting to import a JavaScript file within the app module

Is it possible to import a javascript file into my app module without access to the ts file? import { OtherComponent } from './node_modules/blahblah/OtherComponent.js' While trying to declare this component in @NgModule and running "ng build -- ...

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

Bringing in the Ionic ToastController to a TypeScript class

I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application. Is there a ...

`Angular 9 template directives`

I am facing an issue with my Angular template that includes a ng-template. I have attempted to insert an embedded view using ngTemplateOutlet, but I keep encountering the following error: core.js:4061 ERROR Error: ExpressionChangedAfterItHasBeenCheckedEr ...

Vue Deep Watcher fails to activate when the data is altered

While the countdown timer is functioning properly, it seems that the deep watcher is not working as expected. Despite attempting to log the new value of seconds in the console, it does not display anything even though the countdown timer continues to funct ...

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

What is the best way to incorporate Blob into Typescript?

I am facing an issue while trying to use FileSaver to save a file in Blob format within my TypeScript application. When I attempted to import the Blob module using: import * as Blob from "blob"; An error was thrown: Could not find a declaration file fo ...

Issue with Angular 5 and ngx-intl-tel-input integration

I've been attempting to utilize the ngx-intl-tel-input package. In my module.ts file, I have included the following: import {NgxIntlTelInputModule} from "ngx-intl-tel-input"; import {BsDropdownModule} from "ngx-bootstrap"; @NgModule({ imports: [ ...

React animation failing to render underline animation

After tinkering with the underline animation while scrolling down on Codepen using Javascript, I successfully implemented it. You can check out the working version on Codepen. This animation utilizes Intersection Observer and a generated svg for the underl ...

I am working on a project where I have a parent component that contains a textarea element. My goal is to dynamically adjust the height of this textarea

Is there a way to adjust the size of a textarea component in a child component? textarea.html <textarea style = "height"=150px></textarea> // The height is defined globally here xyz.html <app-textarea></app-textarea> // Looking ...

How to retrieve the parent activated route in Angular 2

My route structure includes parent and child routes as shown below: { path: 'dashboard', children: [{ path: '', canActivate: [CanActivateAuthGuard], component: DashboardComponent }, { path: & ...

Kindly include an @Ionic3Annotation for either @Pipe, @Directive, or @Component

During development, this code runs without any issues. However, when attempting to run it in production using the command: Working: ionic cordova run android Not working: ionic cordova run android --prod --release Error Message: [03:34:41] types ...

What is the importance of including "declare var angular" while working with Typescript and AngularJS?

I've been working on an AngularJS 1.7 application that's coded entirely in TypeScript, and there's always been one thing bothering me. Within my app.module.ts file, I have this piece of code that doesn't sit right with me: declare va ...

Getting access to a variable that was declared in a service class from a component in Angular 9 can be achieved by following

A problem has surfaced in my chat application where the local variable that I set to true in the service class after login is not being accessed correctly from another component. Despite changing it to true, the initial value of false is still being return ...

Directive for displaying multiple rows in an Angular table using material design

I am attempting to create a dynamic datatable with expandable rows using mat-table from the material angular 2 framework. Each row has the capability of containing subrows. The data for my rows is structured as an object that may also include other sub-ob ...

Trouble implementing array filter in React component is a common issue

Hello everyone! I'm facing an issue with deleting an element from my useState array. I have the index of the element that I want to remove, and I've tried the following code snippet: const updatedArray = myArray.filter((item: any, index: number) ...

Angular form: Choose an option by selecting it and clicking on a button

I need help with my Angular form. I want to allow users to select a value when they click on a button. How can I achieve this? page.html <div *ngFor="let product of products; index as i"> <button (click)="chooseProduct(i)">{{product.name} ...

Trouble with Angular 2 template variable not being updated within ngSwitch

My code involves a variable called threadCount that is set based on user input and displayed on the same page. Everything works smoothly with regular interpolation <p>Threads: {{threadCount}}</p> But I also want to append it to specific thre ...