Two-way data binding in Angular 2 is a powerful feature that allows for

My goal is to construct a parent component called Action, which includes two child components named Infos and Localisation. I want to connect the inputs of the children with the parent model.

This is the model:

export class Action{
    title: string;
    location = new Location();
}

export class Location{
    region: string;
    department: string;
}

The parent Component:

import { Component, OnInit } from '@angular/core';
import {InfosComponent} from './infos.component';
import {LocationComponent} from './location.component';
import {Action} from './action';
import { ActionService } from './action.service';

@Component({
  selector: 'form-action',
  template: `

    <h1>Action Form {{currentAction.title}}</h1>
    <infos [title]="currentAction.title"></infos>
    <location [location]="currentAction.location"></location>

    <button  (click)="addAction(currentAction)">Add</button>

    <h2>My actions</h2>
    <ul>
      <li *ngFor="let act of actions">
       {{act.title}} ({{act.location.region}}-{{act.location.department}})
      </li>
    </ul>
  `,
  directives: [InfosComponent,LocationComponent],
  providers : [ActionService]
})
export class ActionComponent implements OnInit{
  currentAction : Action;
  actions : Action[];

  constructor(private actionService: ActionService) { 
       this.currentAction =new Action();
       console.log(this.currentAction);
   }

  addAction(action){
    console.log (action);
    this.actionService.saveAction(action);
  }

  getActions(){
      this.actionService.getActions().then(actions => this.actions = actions);
  }

  ngOnInit() {
      this.getActions();
  }
}

The location component:

import { Component, Input } from '@angular/core';
import {Location} from './action';

@Component({
  selector: 'location',
  template: `
    <h2>Location</h2>
    <p>
        <label for="region">Region: </label>
        <input id="region"  [(ngModel)]="location.region" placeholder="Region"/>
     </p>
     <p>
        <label for="department">Department: </label>
        <input id="department" type="text" [(ngModel)]="location.department" placeholder="Department"/>
    </p>
  `
})
export class LocationComponent {
    @Input("location") location: Location;
}

The infos component:

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

@Component({
  selector: 'infos',
  template: `
    <h2>Information</h2>
    <p>
        <label for="title">Title: </label>
        <input id="title"  [(ngModel)]="title" placeholder="Title"/>
     </p>

  `
})
export class InfosComponent {
    @Input() title: string;
}

When creating a new action, the location is saved but the title is not included in the new action. It works when passing the entire action to the Infos component (not just the title). However, it does not work with a string type.

Answer №1

To achieve two-way binding, you should utilize the @Input xxx; @Output xxxChange syntax like demonstrated below.

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

export class LocalisationComponent {
    @Input() localisation: Localisation;
    @Output() localisationChange = new EventEmitter();

    ngOnChanges(changes: SimpleChanges){
       this.localisationChange.emit(changes['localisation'].currentValue);
    }
}

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

export class InfosComponent {
    @Input() titre: string;
    @Output() titreChange = new EventEmitter();

        ngOnChanges(changes: SimpleChanges){
           this.titreChange.emit(changes['titre'].currentValue);
        }
}

This demonstration is not directly related, but it can provide insight into understanding the mentioned syntax. Visit the plunker demo for more details.

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

Incorrect Column Header Display in React with Kendo-UI Grid

I have a React application using redux as state manager. In this application we are deciding to use Kendo Ui grids. The first test is Ok but we noticed that the columns are totally wrong. We define only 5 Columns to be displayed in the table but we noticed ...

Struggling with setting up Angular Material and SCSS configuration in my application -

Hey there, I encountered an error or warning while trying to launch my angular app. Here's the issue: ERROR in ./src/styles/styles.scss (./node_modules/@angular-devkit/build- angular/src/angular-cli-files/plugins/raw-css- loader.js!./n ...

Utilizing a powerful combination of Angular 5, PrimeNG charts, Spring Boot, and JHipster

I am facing an issue with creating charts using PrimeNG. The main challenge I'm encountering is the conversion of data from a REST API in Angular 5 (TypeScript) and retrieving the list of measurements from the API. I have an endpoint that returns my m ...

I'm having trouble with implementing a basic show/hide feature for the login and logout options in the navigation bar using Angular. Can anyone help me figure out why it's

Is there a way to display the functionality after logging in without using session storage or implementing the logout function? The HTML for navigation is provided below. <nav class="navbar navbar-expand-sm navbar-light bg-light"> ...

Modifying SASS variable within an Angular 2 TypeScript project

How can I update the Sass color variable based on user input in Angular 2? I came across a helpful resource, but it doesn't include any examples specifically for Angular 2. Any assistance would be greatly appreciated. Thank you! ...

Automatically convert user input to MM/DD/YYYY format in typescript as they type the date

Hello, I am currently working on a React Native app where users input their date using TextInput. As the user types, I would like to automatically format the date as MM/DD/YYYY. Here is the function I have created so far: const formatDate(value: string ...

Whenever I try to update my list of products, I encounter an error message stating that the property 'title' cannot be read because it is null

I am encountering an issue with editing data stored in the database. When attempting to edit the data, it is not displaying correctly and I am receiving a "cannot read property" error. HTML admin-products.component.html <p> <a routerLink="/ad ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

An improved method for implementing conditional statements in Angular

After researching online, I came across some discussions about using if else logic in Angular. Although I was able to achieve the desired outcome, I am curious if there is a more efficient or alternative way to implement if else statements in Angular. In ...

Internet Explorer displays a blank page for the Angular app, while it functions correctly in Google

Currently, I am diving into the world of Angular 4 and have created a basic application using Angular CLI (NG New HelloWorld). When attempting to run ng serve and navigate to http://localhost:4200/, the page loads without issue in Chrome. However, when try ...

How to resolve the issue of "NGUniversal window is not defined"

I have a newer version of Angular in my application and recently integrated ng-universal. When I attempt to run the command npm run dev:ssr, an error is thrown with the message: ERROR ReferenceError: window is not defined This error originates from a li ...

Is there a way to identify legitimate contacts and phone numbers within an Android application using Javascript or Typescript?

I am developing an Android app where I need to show a list of contacts and specify if they are part of the app's network. However, my goal is to only display valid contacts while excluding unwanted ones such as toll-free numbers or data balance check ...

The Background Geolocation feature is throwing an error: "Subscribe method is not present in the Promise<any> type."

I am currently using Ionic 4 to build an app that tracks the user's location every hour using GPS. To achieve this, I utilized the Ionic 4 Background Location plugin as per their official documentation. I followed the code to install the plugin which ...

TS2392 error: Implementing multiple constructors in Angular 2 is not permitted

Is there a more efficient way to avoid using multiple constructors in a component? Currently, I am encountering the following error: 'Multiple constructor implementations are not allowed'. questions: any[]; constructor( service: QuestionSignup ...

The kendo-grid-messages are utilized across all columns

I encountered an issue while working with the following code: <kendo-grid-column field="isActive" [title]="l('Status')" filter="boolean"> <kendo-grid-messages filterIsTrue="Yes" filterIsFalse=&qu ...

retrieve the key associated with a translated value using ngx-translate

Using @ngx-translate along with localize-router has posed a challenge for me. I am unable to resolve a valid slug from a localized URL. For example, if the translation of 'about' is 'asd', then: routerLink="about/{{'about' ...

Is there a way to verify if this route leads to a valid page?

I am currently using Angular 5 along with localize-router. Unfortunately, localize-router does not support paths without a language prefix (only the main page), so I decided to create a component to handle this issue. In my router configuration, I have set ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...

Challenge with JWT Tokens

In my application, I am utilizing a Node.JS express backend along with an Angular 4 frontend. The user ID is stored in JWT tokens, which do not expire. Here is the scenario: The user logs in. A JWT Token is generated and signed (containing the user ID). ...

How can I easily move from a shared page to a specific page in Angular 8?

Just stepping into the world of front-end development, I have a scenario where my menu page offers 3 options to navigate: Go to Arena. Go to Dungeon. Go to Battleground. However, clicking on any of these options leads me to a common page for character p ...