Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度6-@输入重复输出4次,而不是1次_Angular_Typescript_Angular6 - Fatal编程技术网

Angular 角度6-@输入重复输出4次,而不是1次

Angular 角度6-@输入重复输出4次,而不是1次,angular,typescript,angular6,Angular,Typescript,Angular6,在一个角度项目中有两个组件 以下是两者的代码: app.component.ts: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { msg() { conso

在一个角度项目中有两个组件

以下是两者的代码:

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-child [message]="msg()"></app-child>
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() {
  }

}
app.component.html:

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-child [message]="msg()"></app-child>
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()

我不知道您为什么要尝试在输入中传递函数,但我在中开发了以下示例

查看应用程序组件。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>

当您传递msg()时,您运行该函数并将其打印到控制台,然后当您收到它时,它再次发生。不要传递函数(console.log),而是传递消息,并且只在子组件中使用console.log。您不想将其放入子html tho,只需将其放入ngOnInit,就像ngOnInit(){console.log(msg);}(其中msg实际上是一个字符串,而不是一个函数)