At times, the Angular global variable may be found to be

I am facing an issue with a component that takes an @Input variable to build a local string in the ngOnChanges method. In my HTML, I have an *ngIf statement checking for this local variable. The problem arises when, even after confirming that the variable has been set, the element is not displayed by the *ngIf directive. To troubleshoot, I added a console log in ngAfterViewChecked to track the value of the local variable, and it switches between undefined and its set value. Despite verifying that the variable is set, the element remains hidden. What could be causing this discrepancy?

.ts

@Input() type: string;

title: string;

constructor() { }

ngOnChanges() {
    console.log('into ngOnChanges');       

    if (this.type) {
        console.log('this.type is', this.type);
        this.title = this.type + ' is the type';
        console.log('title is', this.title);
    }
}

ngAfterViewChecked() {
    console.log('afterViewChecked title is', this.title);
}

.HTML

<span *ngIf="title" class="uppercase">{{title}}</span>

The console logs display:

into ngOnChanges
this.type is something
title is something is the type
afterViewChecked title is undefined
afterViewChecked title is something is the type
afterViewChecked title is undefined

Furthermore, I added a button with a click event to a method that logs the variable value. Surprisingly, it shows as undefined, while subsequent calls to afterViewChecked show 'undefined'...'something is the type'...'undefined'.

.ts

whatIsTitle() {
    console.log('what is title...', this.title);
}

.HMTL (button)

<button (click)="whatIsTitle()" class="btn btn-sm btn-default">Title?</button>

The console logs display:

what is title... undefined
afterViewChecked title is undefined
afterViewChecked title is something is the type
afterViewChecked title is undefined

UPDATE Here's a link to a stackblitz example showcasing the issue further: https://stackblitz.com/edit/angular-yyttwp

When testing on StackBlitz, there are no signs of the problem described above. This leads me to investigate other environment variables within my project that might be influencing the behavior.

UPDATE 2 While exploring the impact of environment variables, I stumbled upon another observation. It seems that the issue extends beyond just a couple of variables. If I add a log of 'this' alongside the earlier log of title in ngAfterViewChecked, I notice that everything in the entire component reverts back to undefined.

.ts

console.log('this is...', this);

Console log in the browser displays:

afterViewChecked title is undefined
afterViewChecked this is... >Component {} 
afterViewChecked title is something is the type
afterViewChecked this is... >Component {type: "something", title: "something is the type" } 
afterViewChecked title is undefined
afterViewChecked this is... >Component {} 

Answer №1

Your title and type are currently undefined, which is why you're experiencing this issue. I've made manual adjustments to initialize these variables, but feel free to customize them based on your specific requirements.

import {Input, OnChanges, SimpleChanges} from '@angular/core'

export class App implements OnChanges{
@Input() type ='hi';

title: string = 'hi';
constructor() { }

ngOnChanges(changes: SimpleChanges) {
console.log('Inside ngOnChanges');       

if (this.type) {
    console.log('The current type is', this.type);
    this.title = this.type + ' is the selected type';
    console.log('Updated title:', this.title);
}
}
whatIsTitle() {
console.log('Checking title...', this.title);
}

ngAfterViewChecked() {
console.log('afterViewChecked - title:', this.title);
}
}

Check out the Plunker demo here

For a more comprehensive guide, refer to the UpgradeComponent class documentation

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

Utilizing a class member's data type

I need to inform Typescript that a member of my class is derived from another class. For instance: Class Main{ getDataFromChild(data){ console.log(data) } } Class Child{ getDataFromChild: Main.getDataFromChild } Scenario Application In my s ...

Enhanced functionality for Thingworx using ThreeJS

I'm currently facing an issue while developing a 3 JS extension for Thingworx, specifically with the renderHtml function when working with a 3 JS canvas (Check out the code). //runtime.ts file renderHtml(): string { let htmlString = '<div ...

Ways to incorporate fresh features through button clicks

Within a table cell, I am using ngClass with a condition like this: <tr> <td [ngClass]="{active: !show, inactive: show}"></td> <td></td> </tr> This ngClass is toggled on button click by the following function: ...

The concept of HttpClient type safety appears to neglect the use of interfaces

TL;DR: A specific angular interface was linked to HttpClient.get() responses. The responses were transformed into a seemingly general object type. Even though attributes like id and title were not defined on the interface, they were still accessible in t ...

Setting up Angular Universal on a Node.js Express server

When it comes to angular universal, whether it's through Angular or Angular-CLI, there are three main components: https://i.sstatic.net/05Wji.png The browser folder Use the command ng build --prod to generate static files The server folder Create ...

How to use Shell command to transfer only HTML files to the designated directory

Currently working on a build script using npm. This build script involves compiling typescript. During the typescript compile process, it copies the folder structure from a ts directory to a dist/js directory. An example of the structure in the ts folde ...

Challenges with displaying css/bootstrap classes within angular2

Experiencing difficulties with CSS/Bootstrap integration when displayed in an angular2 component. When attempting to display the CSS and HTML content in the Index.html file (with proper CSS and JS references), everything functions correctly. However, once ...

Explain a TypeScript function that takes an object as input and returns a new object with only the

Check Playground What's the best way to define a type for this specific function? The inputObject should contain all keys from the enablePropertiesArray and may have additional ones. The function is expected to return a copy of the inputObject, inclu ...

Filtering tables in Angular 6 using checkbox options

I have a functional code snippet that filters a table using checkboxes. However, I am facing an issue when unchecking a checkbox. It does not return the original array as expected. .html <ng-container *ngFor="let group of groups"> <label cla ...

Need to import a custom module using npm and TypeScript

Exploring two projects: main-project and lib-project, both written in TypeScript and compiled to common JavaScript using gulp. Our objective is to require lib-project in main-project. lib-project |-- package.json |-- gulpfile.js |-- dist |-- index.js ...

Ways to refresh drop-down in an angular reactive form

I am currently working with Angular reactive forms and have a dropdown in my form. I am using the reset method to clear my form, but when I do so, the dropdown does not reset. testing.ts file: myMethod() { this.myForm.reset(); } testing.html: <div ...

Creating a versatile field duplication method in TypeScript

I have been trying to create a generic field copy function in TypeScript, but I am struggling to properly define the typing. Refer to method 4 in the code below. My main question is, how can I write a function that ensures TypeScript typing works correctly ...

I'm really puzzled as to why they would choose to export in this manner in React

I noticed that several files were exported in a similar manner, and I'm unsure why this specific method was chosen. Could there be any advantages or particular reasons for exporting them like this? index.ts export { default } from './Something& ...

The inclusion of individual CSS files in a TypeScript React project does not have any effect

My issue involves creating a new react project with typescript and adding a custom component with a separate CSS file for styling. The folder structure is as follows: https://i.sstatic.net/UNtEP.png In the Header.css file, I have defined a class: .mainHe ...

Divide the enhanced document into sections using TypeScript

In my project, I am working with Material UI and TypeScript. I have noticed that I need to declare the Theme interface and ThemeOptions in the same file for it to work properly. Is there a more efficient way to separate these declarations from the main t ...

Mapping data using MapState is a useful technique that can help organize and access data

Is it possible to use ...mapstate to fetch data from the store instead of directly accessing it like this.$store.state.workermanage.staff.staff? Any suggestions are appreciated, thank you. persons: this.$store.state.workermanage.staff.staff ...

Can anyone provide guidance on extracting HTML elements from a stream of objects within rxjs?

In my Angular 8 project, I am working with a WordPress RSS feed to create a news scroller. The information from the feed is parsed into a JavaScript object using rss-parser from node.js. One of the challenges I am facing is extracting a HTTP link, an imag ...

Angular 6: A guide to dynamically highlighting navbar elements based on scroll position

I am currently building a single page using Angular 6. The page is quite basic, and my goal is to emphasize the navbar based on scrolling. Below is the code snippet I am working with: .sticky { position: sticky; top: 0; } #i ul { list-style-type: ...

What is preventing Angular from letting me pass a parameter to a function in a provider's useFactory method?

app.module.ts bootstrap: [AppComponent], declarations: [AppComponent], imports: [ CoreModule, HelloFrameworkModule, ], providers: [{ provide: Logger, useFactory: loggerProviderFunc(1), }] ...

Utilize the useState() hook to add an object and display its data in a React Native

Here is a function I am working with: const [dataLoc, setDataLoc] = useState({date: "No data received yet from sensor", coords: {}}); This is where I set the location: Geolocation.getCurrentPosition( location => { const date = d ...