Unable to achieve any outcomes with the @input directive in Angular

I've seen this question asked before with a lot of answers available through Google search. However, I'm still unable to figure out what I'm doing wrong in passing a value from one component to another. Here's what I have tried:

  <app-dpedit [parentValue]= "testValue"> </app-dpedit>

The testValue is a string variable initialized with a dummy string in the parent.ts file.

In the child component, here's the setup:

@Component({
  selector: 'app-dpedit',
  templateUrl: './dpedit.component.html',
  styleUrls: ['./dpedit.component.css'],
})
export class DPEditComponent implements OnInit {
 @Input() parentValue: string;

When I log the parentValue, it returns as "undefined". I've also attempted using "inputs: ['parentValue']" instead of "@Input", but encountered the same issue. Can someone please help me identify the problem?

EDIT: The entire child ts file has been included below:

import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';

import { GetDataProcessingService } from "../../../service/getServices/get-data-processing.service";
import { ProfileComponent } from "../profile/profile.component";

@Component({
  selector: 'app-dpedit',
  templateUrl: './dpedit.component.html',
  styleUrls: ['./dpedit.component.css']
})
export class DPEditComponent implements OnInit {
 @Input() parentValue: string;

//region variables
  currentURl;
  dataProcessingEditForm: FormGroup;
  formValid = false;
  theDP = {};
  yesNoArray = ["Yes", "No"];
  yesNoFlag = false;
  _ref: any;
//endregion

 constructor(
    private getDataProcessingService: GetDataProcessingService,
    private router: Router,
    private formBuilder: FormBuilder,
    private activatedRoute: ActivatedRoute
  ) {
    this.createForm();
  }

  createForm() {
    this.dataProcessingEditForm = this.formBuilder.group({
      legalReference: ['', Validators.compose([
        Validators.required
      ])],
      Title: ['', Validators.compose([
        Validators.required
      ])],
      Description: ['', Validators.compose([
        Validators.required
      ])],
      dataProcessor: ['', Validators.compose([
        Validators.required
      ])],
      dataController: ['', Validators.compose([
        Validators.required
      ])],
      timeEstimation: ['', Validators.compose([
        Validators.required
      ])],
      justifyDuration: ['', Validators.compose([
        Validators.required
      ])],

      ExistingRecipientName: ['', Validators.compose([
        Validators.required
      ])],
      ExistingRecipientLocation: ['', Validators.compose([
        Validators.required
      ])],

      RecipientYesNo: ['', Validators.compose([
        Validators.required
      ])],
      recipient: [],
      addRecipient: [],

      DSofSectors: ['', Validators.compose([
        Validators.requiredTrue
      ])],
      DTofSectors: ['', Validators.compose([
        Validators.requiredTrue
      ])],
      typeOfProcessing: ['', Validators.compose([
        Validators.required
      ])]
    });
  }

  ngOnInit() {
   console.log("here ===>  " + this.parentValue)
  }
}

Answer №1

In order to make use of the Input decorator, it must be properly implemented:

export class DPEditComponent implements OnInit {
    @Input() parentValue:string;
}

Additionally, as suggested by @Harunur Rashid, it is recommended to utilize double quotes (although this may not always be necessary).

If you are passing a simple string, remember to include single quotes or employ string binding (without brackets):

<app-dpedit [parentValue]="'testValue'"></app-dpedit>
// or
<app-dpedit parentValue="testValue"></app-dpedit>

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

The NGRX state in Angular is not being properly saved by the local storage

Currently, I am utilizing NGRX for state management within my Angular application. While NGRX is functioning correctly, I have encountered an issue with using local storage to persist the NGRX state. Upon refreshing the browser, the NGRX data reverts back ...

When using a custom structural directive, it may not function properly if the selector name does not exactly match

I have created my own custom structural directive in Angular import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[ttIf]' }) export class AppHighlightStrucDirect ...

What is the primary objective of the Angular Elements feature in Angular version 6?

One of the most intriguing features in Angular 6 is Angular Elements, which enables us to convert Angular Components into native Web Components. This means we can utilize them as web components in any framework, such as React or Vue. A critical question a ...

Ionic 6 prioritizes enhanced accessibility by implementing toast blocks that divert attention away from input fields

Scenario: My form is basic, but when the user tries to submit it with invalid inputs, I show a toast message with an error. Issue: Since upgrading to Ionic 6, I noticed that while the error toast is visible, I am unable to focus on any input fields until ...

Is there a way to send routerLink to an HTML element like <div [innerHTML]=""> without triggering the warning: "sanitizing HTML stripped some content"? Check out https://g.co/ng/security#xss for more information

Within the parent component, I am using the following construction: const link = `<a routerLink="${group.id}">${group.name}</a>`; // also tried using [routerLink] When attempting to work with it in a child component, I implement it l ...

Exploring the features of the window object in an Angular application compiled ahead of time

In an effort to streamline our development process and avoid having to build the Angular-App multiple times for different environments, we decided to skip injecting environment-specific variables (such as service endpoints) into our app using regular file ...

How can I invoke a custom function asynchronously with JavaScript?

Incorporating a specific angular third party module into my application has posed some challenges. This module offers various call-back methods such as login success and failure, where I have embedded my custom scripts for execution. However, the current ...

Angular - Automatically blur input field in a Reactive Form

I'm encountering a strange problem. Check out the demo .ts import { Component } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './a ...

Executing Multiple Requests Concurrently in Angular 5 using forkJoin Technique

Important Note The issue lies in the backend, not Angular. The requests are correct. In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin. I store the requests in an array as shown in the code below. However, after adding ...

Tips for improving DOMContentLoaded performance with Angular2

Currently, I am in the process of converting a JQuery template to Angular 2, specifically a Dashboard-like template. This website has numerous popups, each containing multiple tabs, so I decided to separate each popup into different components to keep the ...

Why is it that PowerShell cannot execute Angular commands?

Recently, I started diving into Angular and encountered an issue using PowerShell in Windows. Every time I run an angular command like: ng new new-app or ng serve I keep getting this error message: ng : File C:\Users\< username >\ ...

Navigate to a different route in AntD Table by clicking on it

I am currently implementing React Router in my navigation component. My goal is to enable users to navigate from screen Y to screen X when they click on a table element. In the past, I achieved this by using "this" command but it seems that it does not ...

"Incorporating the node_modules folder into the Express.js compilation process

Is there a way to automatically include dependencies during Express.js compilation, similar to building a React project? I want to avoid dealing with dependencies after the build process. Any suggestions on how to achieve this? I have not attempted any so ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...

Typescript's Class-method concept

I am interested in implementing a class-based method in Typescript where a method defined on a base class can access the subclass from which it was called. While this behavior is possible in Python, I have not found an equivalent in Typescript. What would ...

Should the getDownloadURL() from Firebase Storage be regenerated every time, or can it be reused?

Should I store and reuse the URL received from angularfire2's getDownloadURL() in the database instead of calling getDownloadURL() every time I want to show an image from Firebase Storage? Whenever I use getDownloadURL() in my component, the images a ...

Strategies for Resolving Circular Dependencies in NestJS with GraphQL

Imagine having two different entities: // user.entity.ts @ObjectType() @Entity() export class User { @Field() @PrimaryGeneratedColumn('uuid') id: string; @Field() @Column({ unique: true }) username: string; @Column({ select: fals ...

Having issues with the NX CLI command in my Angular workspace, it is not functioning as expected

Currently, I am in the process of setting up an nx workspace with Angular. Everything seems to be in order as I have installed nx globally. However, whenever I try to launch the nx dep-graph command, a window pops up asking how I would like to open it. Ev ...

What are the steps for changing this JavaScript file into TypeScript?

I'm currently in the process of converting this JavaScript file to TypeScript. However, I've encountered an error with the onClick function as shown below: import React from 'react'; import { Popover } from 'antd'; import A fr ...

Adjusting the audio length in React/Typescript: A simple guide

I'm currently developing a web app with React and TypeScript. One of the components I created is called SoundEffect, which plays an mp3 file based on the type of sound passed as a prop. interface ISoundEffectProps { soundType: string, // durat ...