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

How to Handle Errors When Retrieving an AWS S3 Object Stream in Node.js

I am currently working on developing an Express server that will send items from a S3 bucket to the client using Node.js and Express. I came across the following code snippet in the AWS documentation. var s3 = new AWS.S3({apiVersion: '2006-03-01&apo ...

Exploring the next() function in the Next JS API: A practical guide similar to Express JS

When creating an API in Next JS, I encountered an issue while passing three parameters to my API function (req, res, next). Take a look at the code snippet below: import catchAsyncErrors from "../../../middleware/catchAsyncErrors.js"; import conn ...

Restarting a JavaScript function upon switching views in Vue.js

I am new to working with Vue.js and I have a Laravel app that utilizes it. One issue I am facing is that when the homepage is loading, all elements like owl carousel and rev slider are initialized. However, if I navigate to other routes such as contact or ...

Can you always rely on promises being fulfilled?

Consider a scenario where we have a function named logData to handle HTTP requests and another function called logIntoDatabase. async logIntoDatabase(message) { ... } async logData(request, response) { await logIntoDatabase("something happened"); ...

What could be causing ng-show to fail to hide a div and its content on my page?

Hello everyone, I am brand new to Angular and I have encountered an issue while trying to hide a div and its content within a view. I attempted to use the NgShow directive as outlined in this helpful tutorial: https://scotch.io/tutorials/how-to-use-ngshow- ...

Identify and troubleshoot scripts that are included in the response returned by Chrome

I am facing an issue where I have a webpage that loads HTML sections through an AJAX call. The response includes both HTML and JavaScript files. Currently, I am trying to figure out how to set a debug point on the JavaScript file. In Internet Explorer, I ...

Resolving issues with CSS placement and resizing

I have been considering developing a UI toolkit that offers an intuitive and powerful way of setting the position and size of elements/widgets. Here are some examples of how it could be used (although they are not currently implemented): ui("Panel").size( ...

Looking for assistance with using an array in a for loop with an if-

I'm having trouble with a For loop array. I need to retrieve the data that is opposite of a given function, but when I use arr[i] != elem, it prints out the entire array. On the other hand, if I use arr[i] == elem, it gives me the array that I don&apo ...

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...

How can the service worker be incorporated into an Angular library?

I'm currently working on creating an npm package that will notify users to refresh the page when there's a build update in different projects. I believe using a service worker in Angular can help achieve this concept, however, I encountered an er ...

Toggle button visibility in AngularJS based on checkbox selection

I'm currently utilizing ng-table to construct my table. I have a button positioned at the top of the table that is initially disabled. My goal is to enable this button only when any of the checkboxes are selected. The button should automatically disab ...

What techniques can be used to avoid blinking while forcefully scrolling to the left?

In my previous inquiry about dynamically adding and removing divs on scroll, I was unable to find a satisfactory solution among the responses provided. However, I decided to take matters into my own hands and attempted to implement it myself. My approach ...

Error in accessing the value from the JSON response

After uploading a photo to an external cloud CDN, I receive a JSON response containing relevant information about the uploaded photo. One key piece of data is the public_id field, which I need to store in my database. The response structure is as follows: ...

Tips for refreshing a component after fetching a new page using the useQuery function

Attempting to retrieve and display data from my custom API using axios and react-query's useQuery. The API incorporates pagination, and I have implemented a table with an option to select the page that displays the current data. Everything functions c ...

The debate between using "this" versus "classname" to access static elements in

When working with TypeScript, I've observed that there are multiple valid approaches for accessing a static class member. class MyClass { private static readonly FOO: string = "foo"; public DoSomething(): void { console.log(MyClass.FOO);} pu ...

Managing Datatable with a dynamic header and data is an essential skill that can greatly enhance

I am struggling to handle the Datatable for different header column names with data from my controller. I am passing table headers column name and table data value from my controller. Although I am able to access columns in json within the drawCallback f ...

Verify the accuracy of the properties received from mapStateToProps in a functional React Redux component

I am working with 3 components: TypeList, ConnectedType (connected through connect(mapStateToProps)(Type)), and the component Type. Type will receive props from both TypeList (onClick, name) passing props to ConnectedType as well as ConnectedType's ma ...

"Exploring the Art of Showcasing Duplicate Image Count from User Input in an

I need to showcase multiple duplicates of 2 different images on a webpage. Users are asked for the duplication speed, which I have already implemented, and also how many copies of each image they want. function show_image() { var img = document.create ...

To give an element a class in Javascript (without using jQuery) if it is currently hidden

Apologies if this question is not perfect, as I am still learning. I have been struggling to figure out how to add a class to an ID when the class is hidden using pure JavaScript (without jQuery). Below are my attempts so far: function hidekeep() { ...

Creating a dynamic image display feature using VueJS

Explore the connections between the elements How can I transmit a value from one child component to another in VueJS? The code snippet below is not generating any errors and the image is not being displayed <img v-bind:src="image_url" /> Code: & ...