In Angular-Cli, the variables @Input and @Output are consistently null until they are assigned

Individuals' internal values are printed without any problems, but those obtained using @Input or @Output are not being displayed.

child.component.ts

@Component({
  selector: 'app-form-input',
  templateUrl: './form-input.component.html',
  styleUrls: ['./form-input.component.scss']
})

export class FormInputComponent implements OnInit {
    @Input() fieldType: string;
    //with another Input and 1 Output DOM

 constructor(
    ) {
    }

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

parent.component.html

<app-form-input (value)="action($event)"
    [fieldType]="date"
    [maxAllowItem]="1">
</app-form-input>

Is there a syntax error somewhere? The console always displays 'undefined' in all cases.

Thank you

Answer №1

It appears that the issue lies in referencing a variable defined within the component.

To address this, consider applying the syntax below, enclosing the string within quotation marks to ensure that a string is being passed rather than a component variable. By doing so, the input will be able to recognize and expect a string input.

[fieldType]="'date'"

These actions involve enclosing the string with " and '.

Answer №2

To ensure that your component functions properly, it is important to initialize the initial values of your @Input and @Output variables. This is necessary because @Input properties will default to undefined if not provided externally, and @Output properties must be initialized with EventEmitter.

Additionally, it is recommended to monitor changes using the ngOnChanges method, which is triggered during Change Detection.

Your code snippet should resemble the following:

@Component({
  selector: 'app-form-input',
  templateUrl: './form-input.component.html',
  styleUrls: ['./form-input.component.scss']
})

export class FormInputComponent implements OnInit {
    @Input() fieldType: string;
    @Output() event: EventEmitter<any>
    //along with another Input and 1 Output DOM

    constructor() {
       this.fieldType = ''
       this.event = new EventEmitter()
    }
    ngOnInit() {

    }
    ngOnChanges() { // <- will execute each time, providing the latest value of fieldType
      console.log(this.fieldType);
    }
}

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

Purge the cache of CSS and JavaScript in your browser

Is there a way to clear JavaScript and CSS cache in ASP MVC without having to clear browser history? ...

retrieve dynamically generated content following successful login using cURL

It's common knowledge that curl doesn't process JavaScript, it only fetches static HTML. This is why a simple curl command won't suffice for my needs. I'm not well-versed in PHP, still new to this field. From what I've gathered so ...

Looking for help with aligning an icon to the right side of my text

I'm struggling with aligning the icon to the right of the quantity. When I use float:right, it places the icon at the far right of the cell instead of next to the text. Is there a way to get it to be on the right side of the text but directly adjacent ...

IE11 triggers DatePicker to display as NaN when changing the year

When attempting to manually adjust the year value in the input field rather than utilizing the popup, the datepicker switches the value to "NaN/NaN/NaN". This issue appears to be specific to IE11 as it works correctly in Chrome. ...

Unit testing in Angular involves using the spyOn function to mock classes or functions imported

Trying to ensure a function call from node_modules is made using a spy. For instance, in obs.d.ts: export declare module Obs { class MyService { func(params: Object): Promise<void>; Thus, I aim to spy on func() In my ...

efficiently manage various nested levels of request parameters

I am configuring routes for my express app and need the following paths: /regions /regions/europe /regions/europe/france /regions/europe/france/paris Currently, I have set up individual route handlers for each path. Is there a more efficient way to ha ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...

What is the best way to incorporate additional data into a TypeScript object that is structured as JSON?

I'm exploring ways to add more elements to an object, but I'm uncertain about the process. My attempts to push data into the object have been unsuccessful. people = [{ name: 'robert', year: 1993 }]; //I aim to achieve this peopl ...

How can I update a CSS class value by utilizing AngularJS variables?

I am currently facing an issue with making my CSS values dynamic. The code I have tried is not functioning as expected. <style> .panel-primary { background-color:{{myColorPanel}} } </style> I came across a similar query on Ho ...

Having trouble displaying information in JavaScript after using getScript() to retrieve data from an API containing a JSON block database

I'm a newcomer to the world of Ajax/json/jquery and I find myself with a few inquiries. Currently, I am working with an API located at which contains a JSON block that looks something like this [{"id":"1","FirstName":"Micheal","LastName":"Kooling"}, ...

What is the best way to hold out for a specific number of promises to be fulfilled and halt the resolution of any others

While working in TypeScript, I need to create around 100 instances of Promise. However, I am only interested in waiting for the resolution of 5 of them. Any promises beyond that can either be canceled (if feasible) or rejected since they are no longer requ ...

Can you explain the concept of the "node module wrapper function" in the context of Node.js?

Can someone explain to me the concept of a "module wrapper function" and how it affects my code? (function (exports, require, module, __filename, __dirname) { }); ...

`Testing the functionality of javascript/jQuery events using Jasmine`

I came across this code snippet: $(document).on('click', '#clear-button', clearCalculatedPrice) clearCalculatedPrice = -> $('#price_rule').removeAttr('data-original-title') $('#calculated-price&apos ...

Conceal the current component when navigating in Angular 2

When I swipe on the app.component, I am being redirected to another component. However, the content of the other component is not fully displayed as it is also showing the content of the app.component. How can I hide the app.component content and only di ...

The keys within a TypeScript partial object are defined with strict typing

Currently, I am utilizing Mui components along with TypeScript for creating a helper function that can generate extended variants. import { ButtonProps, ButtonPropsSizeOverrides } from "@mui/material"; declare module "@mui/material/Button&q ...

Leveraging two AJAX requests within a single function

I am working on creating an ajax function to post data that I've retrieved using another ajax function. While I have figured out how to use a callback function, I am struggling with passing the data from one function to the other. Here is what I have ...

How can we determine which MenuItems to open onClick in a material-ui Appbar with multiple Menus in a React application?

While following the examples provided on the material UI site, I successfully created an AppBar with a menu that works well with one dropdown. However, upon attempting to add a second dropdown menu, I encountered an issue where clicking either icon resulte ...

Guide on incorporating jQuery library files into existing application code with the npm command

Recently, I used a node JS yo ko command to create a single-page application using Knockout-JS. Following that, I proceeded to install jquery packages using the command npm install jquery The installation was successful. However, my current goal is to in ...

Filtering DataGrid columns with an external button in Material-UI: A step-by-step guide

Imagine having a datagrid table structured as shown below: import * as React from 'react'; import { DataGrid, GridToolbar } from '@mui/x-data-grid'; import { useDemoData } from '@mui/x-data-grid-generator'; const VISIBLE_FIEL ...

Show or conceal a child component within a React application

In my React render function, I am working with the following code: <div> <InnerBox> <div>Box 1</div> <HiddenBox /> </InnerBox> <InnerBox> <div>Box 2</div> & ...