Troubleshooting issue with @Input not updating model in parent component in Angular 2

The scenario I am facing involves entities that own a Pessoa, with one of them being an Administrador. To handle this, I created a component to encapsulate the Pessoa data on CRUD forms. I linked the administrador.pessoa property to my new PessoaFormComponent using the @Input() directive.

However, I encountered an issue where upon submitting the form in the AdministradorComponent, the administrador.pessoa property remains null. It seems like the updates made to the pessoa property in the PessoaFormComponent are not reflecting back in the AdministradorComponent.

Here is a snippet from administrador.component.ts:

@Component({
...
templateUrl: './administrador.component.html',
directives: [... PessoaFormComponent, ...],
...
})
export class AdministradorComponent {
  @ViewChild('pessoaForm')
  pessoaFormComponent: PessoaFormComponent;
}

And here is a portion of administrador.component.html:

...
<app-pessoa-form #pessoaForm [(pessoa)]="entidade.pessoa"></app-pessoa-form>
...

In the pessoa.form.component.ts file:

@Component({
...
selector: 'app-pessoa-form',
templateUrl: './pessoa.form.component.html',
...
})
export class PessoaFormComponent implements AfterViewInit {
  @Input()
  pessoa: Pessoa;

  private _tipoPessoa: String;

 ngAfterViewInit() {
   this._tipoPessoa= 'FISICA';
   this.reiniciarPessoa();
 }

 private reiniciarPessoa() {
   if (this._tipoPessoa === 'JURIDICA') {
     this.pessoa = new PessoaJuridica();;
   } else {
     this.pessoa = new PessoaFisica();;
   }
 }

 get tipoPessoa(): String {
   return this._tipoPessoa;
 }

 set tipoPessoa(tipoPessoa: String) {
   this._tipoPessoa = tipoPessoa;
   this.reiniciarPessoa();
 }
}

Answer №1

In order for the syntax [(pessoa)]="entidade.pessoa" to function correctly, you must have a combination of @Input() and @Output() where the output name is pessoaChange, and value changes must be emitted using this.pessoaChange.emit(newValue)

export class PessoaFormComponent implements AfterViewInit {
  @Input()
  pessoa: Pessoa;

  @Output()
  pessoaChange:EventEmitter<Pessoa> = new EventEmitter<Pessoa>();

  private resetPerson() {
    if (this._typeOfPerson === 'JURIDICA') {
      this.person = new LegalEntity();
    } else {
      this.person = new NaturalPerson();;
    }
    this.personChange.emit(this.person);
  }

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

Invoking a Components function from a Service in Angular may lead to a potential cyclic dependency issue

I am facing a challenge where I need to call a function from my filterComponent(component) within my engagementService(service). The function in my filterComponent accesses an array that is located within the engagementService. It uses the data from this ...

Injecting dependencies into an abstract class in typescript using Angular 2

So I have an abstract class that doesn't have a constructor, and my goal is to inject another class into it. Here's the abstract class: import { ErrorHandler } from '../../shared/services/errorHandler.service'; import { Inject } from ...

How to Use AngularJS $http Mock Respond to Simulate a Response with a `location` Header?

One interesting scenario I have encountered involves an API that returns a status code of 202 with no data. However, the response includes a header called "Location" which points to a specific URL. After browsing through the $httpBackend respond(...) docu ...

The indexModule module could not be instantiated because of an error: [$injector:modulerr] For more information on this error, please visit http://errors.angularjs.org/1.4.5/$injector/modulerr

While working on one of my projects, I encountered an issue with using ngCookies. Every time I try to inject it, I receive the error mentioned in the title. Here is the HTML code snippet: <script src ="https://cdnjs.cloudflare.com/ajax/libs/angula ...

Exploring Unique Filtering with Angular 2 and Firebase

Looking for guidance on implementing a unique filter with FirebaseListObservable. Here is the data: -key -- name: john smith -- dept: hr -key --name: sam brown -- dept: sales -key --name: nick reyes -- dept: hr How can I make Angular2 display 'hr& ...

When using the combination of Cucumber/Capybara with Angular, the test successfully passes with the Selenium driver but does not work with

I've been attempting to conduct feature tests on an Angular application, but I'm experiencing failures when using the poltergeist driver. It appears that the issue stems from the data-binding syntax being interpreted literally. For example, in th ...

When attempting to display the title of a route in an Angular header component, it consistently results in undefined

I am facing a seemingly simple issue. I have a header component that needs to display the title of the currently active route. To achieve this, I am injecting the ActivatedRoute into the header component and attempting to display the route title using the ...

Exploring Angular2 Heroes Guide - Declaring Hero Properties with Nested Objects

Currently, I am diving into the Angular2 Tour of Heroes guide and striving to grasp the concept of services. So far, I've successfully implemented the basic tutorial, but as I attempt to add more complexity, my application crashes without clear reason ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

The error message "TypeScript reflect-metadata Cannot find name 'Symbol'" indicates that TypeScript is unable to locate

While browsing through http://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators, I encountered an issue where it could not find the Symbol. I was unsure whether this is related to the usage of reflect-metadata or if it was previously in ...

Setting default values for HOCs in React

If I have a higher order component structure like this: interface MyHOCInterface { title: string } export function wrapMyHoc<T extends MyHOCInterface>( Component: React.ComponentType<T>,) { return class extends React.Component<T> { ...

The angular application fails to load the page properly and keeps refreshing itself

I'm currently working on an Angular app that searches for a Github user based on their username and then displays the list of repositories. When a user clicks on a repo name, it should show the open issues and contributors associated with that reposit ...

Using MeanJS to assign a Mongoose object reference to an array in Angular

Having an issue with MeanJS and using the $update function of the $resource service in Angular provided by MeanJS. Here is a basic outline of my problem: Mongoose schema: var mongoose = require('mongoose'), Schema = mongoose.Schema; var Lotion ...

Determine the dimensions of an image using AngularJS

When a user uploads an image with a width of ‘W’ and height of ‘H', the following four constraints must be considered for resizing: 1. The resized image must have the same aspect ratio (width/height) as the uploaded image. 2. The width of the re ...

What are the steps for manually integrating Bootstrap into an Angular project?

I'm currently working on an Angular 5 project within a private domain where I am unable to utilize the npm-install command. As a result, I have manually added Bootstrap's CSS and JS files to my project. I am now unsure how to properly link these ...

Encountered an issue when attempting to include a model in sequelize-typescript

I've been attempting to incorporate a model using sequelize-typescript: type AppMetaDataAttributes = { id: string; name: string; version: string; createdAt: string; updatedAt: string; }; type AppMetaDataCreationAttributes = Optional<App ...

An overview on adding a new element to an array of objects in AngularJS

I have a feature on my website where users can create via points. Each user starts with one point, and if they want to add more, they can click "add" to insert a new object in the array with an empty value. The user then has the option to input a new value ...

Yeoman angular generator problem

While utilizing the angular yeoman generator, I encountered the following error: module.js:340 throw err; ^ Error: Cannot locate module './lib/pack.js' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._lo ...

What steps should I take to create a TypeScript generic class that is limited to only accepting types that are arrays of objects?

I'm working on creating a sample of a generic class in TypeScript. My goal is to have a generic class named RecordsProcessor that is limited to only accept types that are arrays of objects. If I try to pass a number to the constructor, TypeScript cor ...

Typescript decorator specifically designed for abstract generic Container class's child elements

Struggling with Typescript generics in my project, specifically with Typescript 2.6. My goal is to design a MobX store that implements a class decorator for basic authentication checks. This decorator should take a class type derived from the abstract gen ...