子组件ngOnChanges中的演示变量不起作用

问题描述 投票:-1回答:1

虽然在child.component.ts中。我正在将demo变量与input()一起使用。它没有显示在开发人员控制台中

app.html

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

app.componet.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__()

具有输入()的演示变量。它不会显示在开发人员控制台中。

仅显示myValue

angularjs angular angularjs-directive angular-material angular-ui-router
1个回答
0
投票

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

ngOnChanges(changes: SimpleChange }) {
  if(changes['demo'] && changes['demo'].previousValue != changes['demo'].currentValue)
  {
    console.log('The latest value', changes['demo'].currentValue);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.