The situation I find myself in frequently is that the Angular component Input

There seems to be an issue with a specific part of my application where the inputs are not binding correctly.

The component in question is:

@Component({
    selector : 'default-actions',
    templateUrl : './default.actions.template.html',
    styleUrls: [ './default.actions.style.scss' ],
    encapsulation: ViewEncapsulation.None,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DefaultActionsComponent
{
    protected entityId;
    protected uuid = UUID.UUID();
    protected extraForms;

    @Input() protected data;
    @Input() protected structure;
    @Input() protected targetId;
    @Input() protected table;
    @Input() protected row;
    @Input() protected modal: ModalDirective;
    @Input() protected entity;
    @Input() protected entityObject: Entity;
    @Input() protected parentWrapper;
    @Input() protected foo;

    constructor(
        protected translate: TranslateService,
        protected activatedRoute: ActivatedRoute,
        protected actionService: DefaultActionsService,
        protected router: Router,
        protected entityService: EntityService,
        protected http: HttpAuthenticationService
    ) {}

    public ngOnInit() {
        console.log(this.foo);
    }

The component is being used here:

<default-actions
    [table]="table['defaultListingTableComponent']"
    [row]="row"
    [foo]="'bar'"
    [modal]="modal"
    [structure]="availableColumns"
    [entityObject]="entityObject"
    [targetId]="selectedRows()">
</default-actions>

I added the foo input for debugging purposes. However, when I check the console using console.log(this.foo);, it returns undefined. The same issue persists with other inputs as well.

Although all other components in my application are functioning properly, there seems to be some trouble with this particular component that I'm having difficulty identifying.

Answer №1

Have you considered utilizing the OnInit interface to ensure functionality? It might be worth a try.

Answer №2

UPDATE:

Here's a Stackblitz sample I created: https://stackblitz.com/edit/angular-qrgy7k

Helpful Tip:

Instead of directly passing a string like [foo] = "'bar'", consider creating a variable in the parent component and then pass it as [foo] = "yourVariable"

Parent Component HTML:

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>
<app-demo
[mydata]="datatopass"
>  
</app-demo>

Parent Component TS:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  datatopass = "sad";
}

Child Component HTML:

<p>
demo works!
</p>
<div>
  Data: {{ mydata }}
</div>

Child component TS:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit {

  @Input() mydata;

  constructor() { }

  ngOnInit() {
    console.log(this.mydata);
  }

}

ngOnInit() will run when the component is initialized, but at that point, the properties you've bound may not yet contain data from the parent component. You can try using ngOnChanges() or ngAfterViewInit().

One approach is to use Observables and Subjects.

Answer №3

As stated by @Yash, the ngOnInit function is the appropriate place to handle that. However, you could also include the ngOnChanges method and add a console.log within it. Initially, the value may be undefined, but as soon as there are changes in the input, it will trigger and you may retrieve the updated value at that point.


ngOnChanges() {
  console.log(this.bar)
}

Answer №4

Have you ever experimented with using Observables instead? It seems like there might be an issue with your input still being undefined when it is sent to the child component. @Input can sometimes behave strangely if you're not familiar with its functionality.

Answer №5

If you want to test out the implementation of AfterViewChecked, check if the ngAfterViewChecked method contains a value like this:

@Component({
    selector : 'default-actions',
    templateUrl : './default.actions.template.html',
    styleUrls: [ './default.actions.style.scss' ],
    encapsulation: ViewEncapsulation.None,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DefaultActionsComponent implements AfterViewChecked {
    protected entityId;
    protected uuid = UUID.UUID();
    protected extraForms;

    @Input() protected data;
    @Input() protected structure;
    @Input() protected targetId;
    @Input() protected table;
    @Input() protected row;
    @Input() protected modal: ModalDirective;
    @Input() protected entity;
    @Input() protected entityObject: Entity;
    @Input() protected parentWrapper;
    @Input() protected foo;

    constructor(
        protected translate: TranslateService,
        protected activatedRoute: ActivatedRoute,
        protected actionService: DefaultActionsService,
        protected router: Router,
        protected entityService: EntityService,
        protected http: HttpAuthenticationService
    ) {}

    public ngOnInit() {
        console.log(this.foo);
    }

    ngAfterViewChecked() {
      console.log(this.foo);
    }

Answer №6

The issue arises from the usage of ChangeDetectionStrategy.onPush.

When using OnPush, the change detection mechanism operates by comparing the references of the component's inputs. Since the object reference remains constant in your scenario, the OnPush change detector does not detect any changes.

To delve deeper into this topic, you may find more detailed explanations at the following link:

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 it possible to bind an http post response to a dropdown list in Angular?

My goal is to connect my post response with a dropdown list, but the text displayed in the drop-down box shows "[object Object]". My request returns two results - `ArticleID` and `Title`. I want to display `Title` in the dropdown and save the corresponding ...

Tips on implementing conditional validators in Angular's formBuilder

Is it possible in Angular 7.x to use formBuilder and ReactiveForms to apply a validator to a form based on the user's role? For instance, if the user has a specific role, they would be required to input certain fields. The user information is stored i ...

What do you do when schema.parseAsync cannot be found?

Currently facing an issue with zod validation in my Node.js environment, specifically encountering the error: TypeError: schema.parseAsync is not a function Despite attempting various solutions like re-importing and troubleshooting, I am unable to resol ...

Upon receiving the API response, my Angular webpage is failing to redirect to a different page

After executing my code in TypeScript, I encountered an issue with the updateProduct method calling the API to update a product based on form values. The update functionality works fine, but afterwards, I am receiving the following error: error: SyntaxErr ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

How to ensure that Excel recognizes dates as actual dates in a column automatically when using xlsx in Angular

I have a specialized Angular service that is capable of generating excel files: import { Injectable } from '@angular/core'; import * as FileSaver from 'file-saver'; import * as XLSX from 'xlsx'; const EXCEL_TYPE = 'appli ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: If anyone has ...

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

Performing a search through a string array and updating a specific portion of each string

I am faced with an array containing a long list of Strings, and my goal is to filter out all the strings that begin with 'INSERT ALL' and replace the number inside the parentheses with the string ' NULL' Here is the original array: le ...

"Connecting multiple URLs to the same router link: A step-by-step guide

I am currently working on a small test project in Angular and I aim to incorporate a side navigation using Angular router outlet. My goal is to have two links: <a class="nav-link text-white" [routerLink]='["/link/to/one"]' routerLinkActive="a ...

Avoid including any null or undefined values within a JSON object in order to successfully utilize the Object.keys function

My JSON data structure appears as follows: { 'total_count': 6, 'incomplete_results': false, 'items': [ { 'url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2', 'repository_url' ...

Exploring VSCode Debugger with Typescript: Traversing through Step Over/Into leads to JavaScript file路径

Just starting out with VSCode and using it to debug node.js code written in Typescript. One thing that's been bothering me is that when I stop at a breakpoint and try to "Step Over" or "Step Into", the debugger takes me to the compiled Javascript file ...

Troubleshooting Next.js 14.1 Pre-rendering Issue: A Step-by-Step Guide

I just updated my Next.js from version 14.01 to 14.1 and encountered an error during the build process of my application. How can I resolve this issue? The error message reads as follows: Error occurred while prerendering page "/collections". For more inf ...

Angular `CORS` Ailment

I am currently utilizing the MEAN stack (MongoDB, Express, Angular, and NodeJS). I have a basic function for fetching data from an external API as shown below: let api = 'https://thongtindoanhnghiep.co/api/city'; return this.http.get<any>(a ...

Exceed the capacity of a React component

Imagine having a React component that can render either a <button>, an <a>, or a React Router <Link> based on different props passed to it. Is it possible to overload this component in order to accept the correct props for each scenario? ...

Using Typescript and React to assign an array object to state

Here is the situation: const [state, setState] = useState({ menuCatalog: true, menuCommon: true, fetched_data: [] }); An example of data I am trying to set to the state property "fetched_data" looks like this: [{"id": 1, "name": "some_name", " ...

The mat-table's data source is failing to refresh and display the latest

When I click on a column header to sort the table, a function should trigger and update the data. However, the data is not updating as expected. Below is the code for the function and the table: <table mat-table #table [dataSource]="dataSourceMD&qu ...

Error message: In the combination of NextJs and Redux, an issue has occurred where the program is unable to access properties of null, specifically in

I am just getting started with Next and redux, but I am facing an issue. The error shown above occurs when trying to select a redux value from the store. I have attempted using raw useSelector from redux toolkit, but it still results in the same error. ...

Implement FieldResolver in TypeGraphQL for an array of objects

My current dilemma revolves around a specific issue related to the definition of my Cart type, which is structured as follows: @ObjectType() export class Cart { @Field(() => ID) id: string; @Field((_type) => String) ownerId: String ...