How can data be transferred from a parent to a child component in Angular?

I'm facing an issue trying to pass the selected value from a dropdownlist in a user interface. I have a parent component (app.component.html) and a child component (hello.component.html & hello.component.ts).

My goal is to transfer the option value selected by the user from the parent component to the child component. Despite my efforts, it seems there's an error preventing it from working as intended. The browser displays a message saying "failed to compile."

app.component.html

    <h2> Course Details </h2>
    Select a course to view 
    <select #course (change)="name = course.value">
        <option value="Node JS">Node JS</option>
        <option value="Typescript">Typescript</option>
        <option value="Angular">Angular</option>
        <option value="React JS">React JS</option>
        </select><br/><br/>
    <app-hello [cName]="name"></app-hello>

    <router-outlet></router-outlet>

hello.component.ts

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

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

      courses = [
        { courseId: 1, courseName: "Node JS" },
        { courseId: 2, courseName: "Typescript" },
        { courseId: 3, courseName: "Angular" },
        { courseId: 4, courseName: "React JS" }
      ];
      
      @Input() 
      cName: any;

      constructor() { 
        
      }

      ngOnInit(): void {
      }

    }

hello.component.html

    <table border="1" *ngIf="cName">
        <thead>
          <tr>
            <th>Course ID</th>
            <th>Course Name</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let c of courses">
            <td *ngIf="c.courseName == cName">{{c.courseId}}</td>
            <td *ngIf="c.courseName == cName">{{c.courseName}}</td>
          </tr>
        </tbody>
    </table>

Answer №1

The potential issue might lie in the way name is being defined or updated within your app.component.ts, which unfortunately isn't visible in the provided snippet.

To troubleshoot, consider revising the (change) event to trigger a public method in app.component.ts, allowing this method to modify the value of name. Moreover, ensure that name has an initial value specified in your TypeScript file.

Check out the example below:

public name = '';

public updateName(newName: string) {
  this.name = newName;
}

In your HTML template (app.component.html):

<select #course (change)="updateName(course.value)">

Answer №2

The issue arises from the following line as it is not declared anywhere and therefore cannot be used in the template:

<select #course (change)="name = course.value">

You need to create a function for the change event and then utilize a component variable to save and pass the value to a child component like this:

app.component.html

<select #course (change)="updateCourse(course.value)">
<app-hello [cName]="courseName"></app-hello>

app.component.ts

let courseName: string;
updateCourse(name) {
   this.courseName = name
}

Answer №3

While I am not certain about the specific issue causing a "failed to compile" error in your code, I attempted to recreate your code in stackblitz and it ran smoothly.

Perhaps you forgot to declare the Route in the module?

RouterModule.forRoot(appRoutes)

You can view the working code here

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

Why does VSCode open a React app in Edge instead of Chrome?

Recently, I began a new project using the react-create-app template with typescript. However, when I run npm run dev, it unexpectedly opens in the Edge browser instead of Chrome. Does anyone know how to make it open in Chrome instead? ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

Issues with updating data using PUT routes in Slim Framework v3

After upgrading to Slim v3, all my GET and POST routes are functioning correctly, but the PUT routes are encountering issues. I have a class where I have implemented this: $this->slimObj->put('/path/{ID}', array($this, 'method')) ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

Tips for signaling to an AngularJS form that the input value has been altered

I developed a sign up form using angularjs. The submission process is functioning correctly. Now, I want to implement validation to check if the email provided is already registered. If it exists, display an error message indicating that the email is alrea ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

Load an external script once the page has finished loading by leveraging the power of $(document).ready() in conjunction with $.getScript()

Is it possible to load a script in the header of a website instead of at the bottom? I've been trying but it's not working as expected. Here is an example of what I'm attempting: HTML file: <!DOCTYPE html> <html lang="en"> < ...

Tips for preparing HTML content with Jquery's "ON" method?

My jQuery Accordion is functioning properly, but I'm encountering issues when trying to load the accordion content dynamically from a database or JSON onto the page. The problem arises because the DOM doesn't have information about the newly inje ...

What is the best way to set up a server in React using Express or HTTP?

I am currently in the process of developing a web application using react js. In order to create a server for my client within the project, I have decided to utilize either express or http. Here is the code snippet that I attempted: import React from " ...

What is the process for deactivating a range of dates?

I am trying to prevent users from selecting dates within the range specified by l1 and l2. However, my current method only disables the date 13. var l1 = new Date("2019-07-13"); var l2 = new Date("2019-07-30"); this.flag = 0; this.filter2 = function( ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

What's the most effective method to incorporate additional events into this element using the conditional operator?

Looking for help with this code snippet: <span role="link" tabindex="0" :class="tabDetails.showPayment ? 'link' : ''" @click="tabDetails.showPayment ? cTab('payments') : null" ...

Which data types in JavaScript have a built-in toString() method?

Positives: 'world'.toString() // "world" const example = {} example.toString() // "[object Object]" Negatives: true.toString() // throws TypeError false.toString() // throws TypeError Do you know of any other data types that wi ...

Mocha avoids running the test

Hi everyone, I am a beginner in Node.js and JavaScript and I'm having trouble understanding why Mocha is skipping over my test. I know that I may not be using the request and supertest libraries correctly, but I really want to figure out why, when it ...

How to Incorporate and Utilize Untyped Leaflet JavaScript Plugin with TypeScript 2 in Angular 2 Application

I have successfully integrated the LeafletJS library into my Angular 2 application by including the type definition (leaflet.d.ts) and the leaflet node module. However, I am facing an issue while trying to import a plugin for the Leaflet library called "le ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

How can I implement a master-detail view in Angular 2?

Update: I finally figured it out. After moving all the html from index.html to app.component.ts, everything started working perfectly. The method described below is the correct one. I've been facing an issue where I have a ParentComponent that retrie ...

What is the best way to transfer form data to another function without causing a page refresh?

Currently, I am in the process of developing a series of web applications using REACT JS. One specific app I am working on involves a modal that appears upon a state change and contains a form where users can input their name along with some related data. ...

What is the best way to create shared scope and transmit data within an Angular directive?

In my angular directive, I have the following code: app.directive('myDir', function () { return { restrict: 'E', scope: true, template:'<div>{{myindex}}</div>', link: function(scope, element, att ...