Initializing variables in Angular2 templates

I am facing an issue where, upon running the application, the console displays all the logs from the ngOnInit function, but the actual view only shows a skeleton without the component variables and text from l18n. It seems like the ngOnInit is not working properly and needs to be called in the constructor.

Interestingly, the problem disappears when I click on a link to a component for the second time. Everything loads correctly as expected. This issue is persistent across all components in the application built on the angular2 starter gulp.

I'm curious as to why the variables are only loaded and ngOnInit is called properly on the second click. Any insights into this behavior?

export class SettingsDevicesComponent implements OnInit {

**variables**

@Component({
  selector: 'as-settings-devices',
  templateUrl: 'app/settings-devices/settings-devices.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrls: ['app/settings-devices/settings-devices.component.css'],
  providers: [Communication],
  pipes: [TranslatePipe],
  directives: [REACTIVE_FORM_DIRECTIVES, NgClass, NgStyle, CORE_DIRECTIVES,ROUTER_DIRECTIVES]
})

constructor(private _cm: Communication,
            private _cdRef: ChangeDetectorRef,
            private _router: Router,
            private _sanitizer: DomSanitizationService,
            @Inject(ElementRef) elementRef: ElementRef
            ) {
                this.elementRef = elementRef;
                this.ngOnInit();
                this.fileUpload = new FormGroup({
                    color: this.color
                });
                this.fileName = new FormGroup({
                    fileNameInput: this.fileNameInput
                });
                this.settingsName = new FormGroup({
                    settingsNameInput: this.settingsNameInput
                });
            }

ngOnInit() {
    this.getDeviceData();
    this.getZoneData();
}
}

Answer №1

The issue arose from having the changeDetection set to ChangeDetectionStrategy.OnPush in the main component 'app.component.ts'

This is the problematic code snippet:

@Component({
  selector: 'as-main-app',
  templateUrl: 'app/app.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  directives: [ROUTER_DIRECTIVES]
})

Once the changeDetection was removed, everything functioned properly:

@Component({
  selector: 'as-main-app',
  templateUrl: 'app/app.html',
  directives: [ROUTER_DIRECTIVES]
})

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

Is there a way to use an Angular interceptor to intercept and modify static files like .html files? I would like to change the lang

While researching Angular intercepting, I stumbled upon this helpful documentation: here. My goal is to intercept HTML using an Angular interceptor in order to modify the HTML file before it's displayed in the browser. Trying to accomplish this on the ...

Badging with Angular, HTML, and Bootstrap

I've been attempting to integrate Bootstrap 5's badges into my Angular application, but they don't seem to be displaying correctly together. While using Angular 13, the html within the app-root component appears clustered without proper for ...

Angular2 (AngularCLI) cannot locate the Elasticsearch module

Currently, I am attempting to incorporate the Elasticsearch NPM Module into my Angular2 application. In order to use it in my service, I have imported it as follows: import { Client, SearchResponse } from 'elasticsearch'; Even though there are ...

Utilize TypeScript to match patterns against either a string or Blob (type union = string | Blob)

I have created a union type called DataType, type TextData = string type BinaryData = Blob type DataType = TextData | BinaryData Now, I want to implement it in a function function processData(data: DataType): void { if (data instanceof TextData) ...

Using SQLite to handle JSON data

I am currently working with Ionic2/Angular2 framework. My aim is to save data on the user's device or browser. While Local Storage seems like an option, I have concerns about its reliability. Although SQLite is a dependable choice, it uses SQL inste ...

Ways to develop a dynamic Promise-returning Function

I find myself in a situation where I am aware of the type of data that will be returned when making a request to an API. Here is the function I have: const fetchData = async (url: string, options?: Object): Promise<any> => { const res = await f ...

Deploying a single Angular 5 project to various clients with unique URLs can streamline the development process

I am currently working on a new project using Angular 5.2 version. It has been deployed to the DEV location with the following URL: http://XX.XX.XX.XX/myDev/app/login When I execute the ng build command: ng build -aot -ec --prod --base-href=/myDev/ Now ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

Can you explain how TypeScript module resolution handles global values?

After installing @types/jest, I noticed that jest's corresponding typescript definitions were detected automatically. However, when I started implementing integration tests with cypress (which uses mocha), I encountered a problem where mocha type defi ...

Angular2 Dropdown Menu with Arrow Key Scrolling

When you interact with the Select Market feature in the following plunk, an Observable is filled with data in an array format. The initial item in the list is highlighted in yellow due to a 'selected' property being set. However, there is an issu ...

Alerts created with the AlertController in Ionic 4 Angular are not displaying the message when the

After creating a reliable alert service for my Ionic 4 project, I encountered an issue when building the release version of the app. Despite functioning perfectly in other environments like "ionic serve" and "ionic cordova emulate", the message part of the ...

How can I utilize generic types in Typescript/React when crafting a component with prop types?

I am facing an issue with a component that has a generic definition as shown below: export type CheckboxItem = { label: string, code: string, }; export type CheckboxesProps = { items: CheckboxItem[], handleStateChange: (selected: (CheckboxItem[&ap ...

Issue with offline functionality in Angular 4 project

I am currently working on an E-commerce Project utilizing Angular 4, Bootstrap, and font-awesome. Additionally, I have incorporated .scss files, angular-cli, and have custom-built a slider component. All libraries, images, and necessary files have been ins ...

The system couldn't locate the module: Issue: Unable to find module 'fs' within the directory

I am currently working on integrating the ADAL JS sample code from this link into a SharePoint framework client web part. My code is fairly straightforward, as I have already installed packages like adal, fs, and node-fs using NPM. However, when running t ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...

Error TS2339: The 'email' property is not found in the 'FindUserProps' type

interface FindUserEmailProps { readonly email: string } interface FindUserIdProps { readonly id: string } type FindUserProps = FindUserEmailProps | FindUserIdProps export const findUserByEmail = async ({ email }: FindUserProps): Promise<IUser&g ...

Concealing a VueJs component on specific pages

How can I hide certain components (AppBar & NavigationDrawer) on specific routes in my App.vue, such as /login? I tried including the following code in my NavigationDrawer.vue file, but it disables the component on all routes: <v-navigation-drawer ...

Tips on maintaining the chosen product while navigating to a different component

I have a dilemma with 2 different components that are responsible for creating an invoice. The first component adds more products The second component adds invoice details Initially, I enter the invoice details and select the client's name. The sel ...

IntersectionObserver activates prior to element's entrance into the viewport

I've set up a Vue component with the following structure: <template> <article> <!-- This content spans several viewport heights: you *have* to scroll to get to the bottom --> {{ content }} </article> <span ref ...

Error encountered: The import of 'createLocation' from 'history' failed. This issue occurred due to conflicting versions of History and React-Router-DOM

While attempting to configure an existing project on a new development server, I encountered the following error: ./node_modules/react-router-dom/esm/react-router-dom.js Attempted import error: 'createLocation' is not exported from 'histor ...