Having trouble with Angular 2 @input binding?

Parent module:

import {NgModule} from '@angular/core';
import {SharedModule} from "app/shared/shared.module.ts";

import {HeaderComponent} from './header.component';
import {UserinfoComponent} from './userinfo.component';
import {SearchComponent} from './search.component';
import {DropdownComponent, DropdownValue} from '../../forms/dropdown.component';

@NgModule({
    declarations: [
      HeaderComponent,
      UserinfoComponent,
      SearchComponent,
      DropdownComponent,
    ],
    imports     : [SharedModule],
    exports     : [HeaderComponent],
})

export class HeaderModule {
  items: DropdownValue[] = [
    {value: '1', label: 'test 1'},
    {value: '2', label: 'test 2'}
  ];
}

Module html:

<div class="navbar dark-bg remove-bottom-margin flex-container">
    <search></search>
    <div class="flex-item">
        <dropdown [items] = "items"></dropdown>
    </div>
    <userinfo></userinfo>
</div>

Component:

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

export class DropdownValue {
  value: string;
  label: string;

  constructor(value: string, label: string) {
    this.value = value;
    this.label = label;
  }
}

@Component({
  selector: 'dropdown',
  template:  `
    <select class="form-control" [(ngModel)]="selectedValue.value" (change)="onChange($event)">
      <option *ngFor="let item of items" [value]=item.value>{{item.label}}</option>
    </select>
  `,
})

export class DropdownComponent {
  selectedValue: DropdownValue = new DropdownValue('2', '');

  @Input()
  items: DropdownValue[];

  @Input()
  value: string[];

  @Output()
  valueChange: EventEmitter<any> = new EventEmitter();

  onChange(event: any) {
    console.log(event.target.value);
    this.valueChange.emit(event.target.value);
  }
}

If I populate the test data within the component and eliminate data binding - it functions correctly.
I also attempted a simple approach like @input items: string and displayed it as plain text in the template. However, it remains undefined.

What could I be overlooking? I've reviewed examples but am unable to spot any discrepancies.
Is there a specific import required in the module for the data binding to operate?

Answer №1

After much trial and error, it became clear that the databind value needed to be set within

import {HeaderComponent} from './header.component';
itself rather than in the importing module.

Answer №2

Ensure that you include all necessary modules, especially those that may be shared with other imports like

import {CommonModule} from "./app/common/common.module.ts";

Check out the demo for the slideshow component.

Answer №3

Start by including the following:

options: Selection[] = [
    {value: '1', label: 'example 1'},
    {value: '2', label: 'example 2'}
  ];

In a different component such as abc, make sure to import it in your module. Next,

<selection [options] = "options"></selection>

in this code, [options] should correspond to the property name specified with @Input in your component class and "options" should match the property name used in abc component class...

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

Angular 2 + Meteor already has a "collection" in its repository

import {Mongo} from 'meteor/mongo'; export let Products = new Mongo.Collection('products'); This code snippet is part of my sample project. However, when I attempt to run the project, an error is thrown. The error message reads: "Th ...

Using dangerouslySetInnerHTML in ReactJS can potentially strip away data attributes

After adding a data-test attribute to the a anchor tag within an HTML string and inserting it using dangerouslySetInnerHTML, I noticed that the data attributes are somehow being stripped out. Is there a way to prevent this from happening? These attribute ...

`Square payment integration using the mean stack technology stack`

Seeking advice on how to integrate Square payment form with angular and node. The form functions properly, but upon hitting send, it fails to post to /process-payment. As a newcomer to the MEAN stack, I am unsure where to start regarding using angular and ...

Creating an async function in TypeScript to retrieve the coordinates of a particular location is a useful way to streamline the

I am looking to retrieve the coordinates of a location as the output of a function. The coordinates are already assigned within a fetch method, with latitudes stored as coordinates.lat and longitudes stored as coordinates.lng. [Currently, it is returning ...

The conversion of a newline in an Angular page is done using &lt;br/&gt tag

Here is a function I have: setLocalVariableOnAccepted(ogp, hb, responseJson) { if (responseJson.ofgp === undefined) { this.ogpStatus = 'orange'; this.ogpStatusMsg = responseJson.ofgp + ', <br/> No change. Previous va ...

The issue at hand in Ionic 2 / Angular 2 is that the NPM module is being utilized as a value instead of referring to a type

I'm currently working on integrating the npm module "ajv" into my Ionic 2 (Angular 2) project. You can find more information about this module at . After running "npm install ajv --save", I proceeded to make some modifications to my app.modules.js fi ...

Sorry, it seems like there is an issue with the Typescript error that states: "The expression you are trying to call is not valid. The type 'typeof import("koa-session")

Partially resolved: An issue has been identified on Github regarding this problem. It seems that declaring a module in a global scope rewrites the types of the entire exported module, while declaring a module within another module merges the types. This b ...

I am puzzled as to why I am still facing the error message: "'node' is not recognized as an internal or external command, operable program or batch file."

I'm in the process of setting up typescript for a new node project. Here are the steps I've taken so far: Installing typescript: npm i --save-dev typescript Installing ts-node: npm i --save-dev ts-node Installing the types definition for node ...

Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads: // The target function function original (a: number): boolean; function original (a: string): boolean; function original (a: boolean): bool ...

Using an asynchronous for loop to assign a background image to a div element

I am facing an issue with setting the background image of an observable array in my Ionic application. Here is the code snippet I am using: <ion-card *ngFor="let picture of pictures$ | async;" <div class="user-image" [ngStyle]="{'background- ...

Can you explain the distinction between Array<string> and string[]?

Can you explain the contrast between Array<string> and string[]? var companies: Array<string> = ['Samsung', 'Sony', 'LG']; var businesses: string[] = ['Lenovo', 'Asus', 'Acer']; ...

Issues with routerLinkActive

On my page, I have a menu that uses the routerLinkActive attribute to add a green background when a link is active and grey when it's not. However, I'm facing an issue where the bg-success class is added but doesn't overwrite the bg-dark cla ...

How to efficiently manage multiple input fields with a single ref in React using TypeScript

I'm attempting to use the same reference for multiple input fields in my form. However, when I log it, the ref only points to the first input field. Is there a way I can share the same ref across different inputs? import React, {FC, useEffect, useRef, ...

Unraveling NGRX: a guide to invoking factory selectors from within additional selectors

NGRX has deprecated selectors with props in version 11. The recommended method now is to create factory selectors. How can you nest selectors or call one from another and pass the state between them? Prior to the change, if we had the following two selec ...

Determine the type of input and output based on another argument

When working with a function that takes an object of either TypeA or TypeB, the first parameter is used to specify the type of the object and the returned type depends on this first parameter. The issue arises in TypeScript where the type of the object is ...

Utilizing Angular 11's HostListener to capture click events and retrieve the value of an object

Using the HostListener directive, I am listening for the click event on elements of the DOM. @HostListener('click', ['$event.target']) onClick(e) { console.log("event", e) } Upon clicking a button tag, the "e" object contains the fol ...

Form validation errors were detected

Currently, I am working with a formgroup that contains input fields with validations set up in the following manner: <mat-form-field class="mat-width-98" appearance="outline"> <mat-label>Profession Oc ...

typescript: declaring types in a separate JavaScript file

Imagine you have a JavaScript library that exports some types for use (let's call it js1.js). You also have some TypeScript code sitting in a <script type="module"> tag that you want to use these types with (let's say ts1.ts). To make this ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

HTTP Interceptor never finishes executing (finalization is never triggered)

In my angular 8 project, I created a basic HttpInterceptor that simply duplicates the original request and includes an additional parameter: @Injectable() export class RequestHeadersInterceptor implements HttpInterceptor { intercept(request: HttpReques ...