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 {}