Search code examples
angularangular-services2-way-object-databinding

Angular cannot bind data from parent component


parent component emit data via service to the child component, but I cannot bind data to the child component (in select):

<!-- Parent -->
<div class="form-group">
  <label for="projects" class="text-dark ">Projects:</label>
  <select class="form-control" id="projects" name="project" [(ngModel)]="selectedProject">
      <option *ngFor="let projectElement of projects"
          [ngValue]="projectElement">{{projectElement.name}}</option>
    </select>
</div>

<!-- Child -->
<app-tasks [project]="selectedProject?.tasks"></app-tasks>

When there is whole HTML structure of the child component in HTML file of the parent component, it works fine, but I want to separate child component with selector like in the example above.

What's wrong in binding?

Stackblitz


Solution

  • Is this what you are trying to do?

    I just changed your tasks component to reference your tasks. you had a variable in there that didn't exist so i just changed it for you

        <option *ngFor="let task of this.project">{{ task.name }}
    

    also i added a ngOnChanges for your console log just to show the output

      ngOnChanges() {
         console.log(this.project);
      }
    

    https://stackblitz.com/edit/cascading-dropdown-jewucx