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

Building an Angular and NodeJS application with Mongoose pagination capabilities

I have a question regarding the design aspect of my project rather than delving into lots of code. My angular client interacts with a MongoDB collection through an HTTP call to a Node.js backend. I am looking to implement pagination for the results. To ach ...

The console is displaying a promise that is pending, rather than the desired data

Here is the content of my file: 'use strict' import * as moment from "moment"; import { Report} from "./Report"; import { Timeframe} from "./Timeframe"; import { ReportComparison } from "./ReportComparison"; function test(firstFrom: string, fi ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

Sending asynchronous data from parent to child components in Angular

When utilizing Angularfire2, my goal is to transmit an object retrieved from the Firebase database from parent to child components: Parent Component: @Component({ selector: 'app-page', styleUrls: ['./page.component.scss'], templ ...

Navigate to a different page using Angular with a simple click

How can I implement a redirect from clicking on the "Firms" word to another component page in Angular? I have tried using routerLink="/", [routerLink]="['/']". I have imported Routes in the app.module. I have also attempted this approach: import ...

Are you familiar with Mozilla's guide on combining strings using a delimiter in Angular2+?

I found myself in need of concatenating multiple string arguments with a specific delimiter, so after searching online, I stumbled upon a helpful guide on Mozilla's website that taught me how to achieve this using the arguments object. function myCo ...

The error message "Uncaught TypeError: emit is not a function in Vue 3" indicates

As I implemented the code in the Vue 3 setup block to retrieve the input value according to this answer, here is a snippet of the code: import { defineComponent } from "vue"; import { defineProps, defineEmits } from 'vue' export defaul ...

How to verify if an unknown-type variable in TypeScript contains a specific property

When using typescript with relay, the props passed down are of type unknown. Despite my efforts, I am unable to persuade the compiler that it can have some properties without encountering an error: <QueryRenderer environment={environment} query={te ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

Transporting a Typescript file to the customer using JavaScript

As a newcomer to typescript and in the process of creating a small application in visual studio 2013, I have noticed that when viewing the project in Chrome's developer tools, typescript files (*.ts) are being downloaded to the client. This could pote ...

Angular Material 2 Stepper Controls for Angular applications

I successfully implemented a linear stepper using the Angular Material 2 Stepper component. My project consists of forms in various components (component-a, component-b, component-c). I need the linear stepper in my main container component (container-com ...

Access data from JSON array in Angular 2

I'm facing a basic issue here. I have a JSON file named pageDefinition.json that is being loaded into my component. Here's how the JSON data looks: ... "testArray": [ {"id": 0, "name": "row1"}, {"id": 1, "name": "row2"}, {"id": 2, "n ...

The attempt to combine an array of elements with another array using FieldValue.arrayUnion() in Firestore was unsuccessful

My cloud function is triggered when a specific event occurs. Within the function, I receive an array of strings like this example: let h:string[] = ["foo","bar","baz"]. When I attempt to update an array field within my document using names: admin.firestor ...

Methods for closing a modal popup on button click

In my AppComponent, there is a login button that triggers a SigninComponent modal popup when clicked. I am trying to figure out how to close the opened modal popup when a button is clicked. Below is the code snippet: app.component.html <ng-template # ...

Cookies are not being sent by Angular 2

Currently, I am working on a project that involves frontend development using angular 2 and backend with symfony as the API. However, I am facing an issue where I need to send the PHPSESSID when making a request to symfony, but it is not happening as expec ...

"Learn how to extract the image URL from the configuration file (config.json) within the assets folder, and then seamlessly display it within

In my Angular project, I have a configuration file located in the assets folder: { "brandConfig": "brand1", "brand1": {"urlPath": "http://192.168.168.60:8081/mantle-services", " ...

Using Rust WebAssembly in Next.js

Seeking assistance with integrating a rust-generated wasm module into my NextJS project. This is how I am attempting to import the wasm: import init, { tokenize } from "@/wasm/lazyjson"; const Test = dynamic({ loader: async () => { ...

When attempting to create a new page in Ionic 5, the error message "**An NgModule could not be located**" is being displayed

While attempting to create a page using ionic g page pages/first, I encountered the following error: Could not find an NgModule. Use the skip-import option to skip importing in NgModule. [ERROR] Could not generate page However, when I tried ionic g page s ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

Diverse Selection of Font Awesome Icons

In my React project with TypeScript, I have a header component that accepts an Icon name as prop and then renders it. I am trying to figure out the best way to ensure that the icon prop type matches one of the existing FontAwesome Icons. import { FontAwe ...