Angular 6 - Receiving @Input causes output to multiply by 4 instead of displaying just once

In my Angular project, I have two components set up. Here is the code for both:

app.component.ts:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  msg() {
    console.log('my message');
  }

}

app.component.html:

<app-child [message]="msg()"></app-child>

child.component.ts:

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

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

  @Input() message: string;

  constructor() {}

  ngOnInit() {
  }

}

child.component.html

{{ message }}

The issue at hand is that the console message generated by msg() is being repeated 4 times instead of just once. How can this be fixed to ensure that msg() runs only one time?

Answer №1

I'm not sure why you are attempting to pass a function inside of Input, but I have created an example on StackBlitz for reference.

Feel free to check out the code in the app-component.ts:

export class AppComponent implements OnInit  {

  message: string;
  ngOnInit() {
    this.displayMessage();
  }
  displayMessage(){
    this.message = "Show Message";
    console.log("Message");
  }
}

HTML:

<app-child [message]="message"></app-child>

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

Bring in a collection of classes of various types from one TypeScript file to another

In my code file exampleA.ts, I define an object as follows: import { ExampleClass } from 'example.ts'; export const dynamicImportations = { ExampleClass }; Later, in another file named exampleB.ts, I import an array that includes class types and ...

Guide on transforming an array of objects into a fresh array

I currently have this array: const initialData = [ { day: 1, values: [ { name: 'Roger', score: 90, }, { name: 'Kevin', score: 88, }, { name: 'Steve&apo ...

A powerful trio: Axios, Typescript, and Promises

I am facing a TypeScript dilemma. I have a REST method that is being called within my http library by Vue action. I want the resolve() method to return the typed array, but if I do not convert it within the action.ts "then" method, I get a '.length do ...

The issue with ngx-bootstrap-modal is that it fails to interpret HTML elements

In my Angular 5 project, I am implementing ngx-bootstrap-modal. Below is the code I am using to open the modal: this.dialogService.addDialog(PopUpComponent, { title: 'Custom locale', message: "Hello ? " }).subscribe((isConfirmed ...

"Implementing an Angular route component that adjusts based on specific

I am currently working on routing within my application for the 'feed' module. Within this feed, there are two types of posts that I need to display with a direct link to show full information. How can I ensure that the right component is opened ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

Exploring data retrieval from nested arrays of objects in TypeScript/Angular

I have an API that returns an object array like the example below. How can I access the nested array of objects within the JSON data to find the role with roleid = 2 when EmpId is 102 using TypeScript? 0- { EmpId: 101, EmpName:'abc' Role : ...

The typed union type FormGroup in Angular stands out for its versatility and robustness

Within my application, users select a value from a dropdown menu to determine which type of FormGroup should be utilized. These formGroups serve as "additional information" based on the selection made. I am currently working with three distinct types of f ...

Testing the Binding of Models in Angular 5 Using Jasmine Framework

I'm currently working on writing a unit test to verify that the JSON data returned from the components method call successfully links to a TypeScript model. Here's what my model looks like: export interface IPlayerAccount { playerId: number; ...

Having trouble creating a dynamic form in Ionic

I am in need of creating a dynamic form. Here is the desired output: {"laboratories":[{"colArr":[{"col":"11"},{"col":"22"},{"col":"33"}]},{"colArr":[{"col":"5"},{"col":"423"}]}]} The key laboratories represents the number of rows. Each row contains the k ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Does Nativescript have a feature similar to "Hydration"?

It's been said that Phonegap offers an exciting feature called Hydration, which can lead to rapid and efficient deployments when combined with CD. Is it feasible to incorporate this concept into a Nativescript application? While I may not be well-ve ...

What is the best way to utilize angular2 components based on their name using ngFor?

Check out the components I've created: app-widget-resume app-widget-my-courses-learner app-widget-my-courses-teacher app-widget-my-calendar app-widget-virtual-classes I want to populate my dashboard component, called my-dashboard, by util ...

Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console. ERROR TypeError: feature_r5.get is not a function at PostAdvComponent_ ...

Multiple values are found in the 'Access-Control-Allow-Origin' header in Angular 7

After serving my Angular app on port 4202, I attempted to connect to a remote Spring MVC app using the code snippet below. this.http.post<Hero[]>('http://localhost:8080/api/hero/list', {"id":1}, httpOptions) However, I encountered the fol ...

The in-memory-web-api is failing to respond to queries when using Chrome

I've been experiencing an issue with my in-memory database setup. Even though I have registered everything correctly, I am not receiving any data back. There are no errors or 404 responses; it seems like the app is intercepting the request and returni ...

Angular Ahead-of-Time (AOT) compilation causes multiple route definitions to be

Having a bit of trouble configuring ahead-of-time compilation for my lazy-loaded Angular app. The lazy-loaded routes are specified in the app.routes.ts file, which is imported by app.module.ts. Running ngc results in the content of app.routes.ts being mer ...

Obtain the input value from a modal and receive an empty string if no value

Utilizing ng-multiselect-dropdown within my bootstrap modal allows users to choose multiple products. Each time an item is selected (onItemSelect), a new div is inserted using the jQuery method insertAfter(). This new div displays the quantity of the selec ...