首页 > 解决方案 > 子组件 ngOnChanges 中的 Demo 变量不起作用

问题描述

虽然在 child.component.ts 中。我正在使用带有 input() 的演示变量。它没有显示在开发者控制台中

应用程序.html

<input type="text" placeholder="text" #val>
<br>
<button (click)="submitValue(val)">submit</button>
<app-child [myValue]="value"></app-child>

应用程序组件.ts

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

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


  value : string;
  submitValue(val){

    this.value=val.value;

    console.log(this.value);
  }
}

child.html

<p>from child...!</p>
<strong>{{myValue}}</strong>

child.component.ts

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

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

  constructor() { 

    console.log('constructor called');

  }

  @Input() myValue='ux trend';
  @Input() demo='';

  ngOnInit() {
  console.log('onInit called');

  }

  ngOnChanges(changes : SimpleChanges){

    console.log(changes);
  }

}

在 Chrome 开发者控制台中,我看到:

{myValue: SimpleChange}
myValue: SimpleChange {previousValue: undefined, currentValue: undefined, firstChange: true}
__proto__:
constructor: ƒ Object()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
hasOwnProperty: ƒ hasOwnProperty()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toString: ƒ ()
valueOf: ƒ valueOf()
toLocaleString: ƒ toLocaleString()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

带有 input() 的演示变量。它没有显示在开发者控制台中。

只显示 myValue

标签: angularangular-materialangular-ui-router

解决方案


带有 input() 的演示变量。它没有显示在开发者控制台中。

是的,因为您没有将它传递给ChildComponent.

您当前的代码:

<app-child [myValue]="value"></app-child>

所以要检测它,

<app-child [myValue]="value" [demo]="someAmazingText"></app-child>

如果要检查myValue变量是否已更改或要访问当前值,则必须使用:

ngOnChanges(changes: SimpleChange }) {
  if(changes['myValue'] && changes['myValue'].previousValue != changes['myValue'].currentValue)
  {
    console.log('The latest value', changes['myValue'].currentValue);
  }
}

推荐阅读