Angular 6 - @Input 重复输出 4 次而不是一次

Angular 6 - @Input repeats output 4 times instead of one

我在一个 angular 项目中有两个组件。

这是两者的代码:

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 }}

如您所见,msg() 将在控制台上输出一条消息。

问题是控制台消息重复了 4 次而不是 1 次

我怎样才能解决这个问题,让它只 运行 的 msg() 一次?

我不明白你为什么要在 Input 中传递函数,但我在 stackblitz

中开发了以下示例

看看app-component.ts

export class AppComponent implements OnInit  {

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

HTML

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