angular - 子组件 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
解决方案
带有 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);
}
}
推荐阅读
- node.js - Express.js 和 NodeJs,在 url 查询中丢失 (+)
- c# - 条形码生成完美,但是当我打印 2 个或更多时,它会在另一页上打印每个条形码
- android - 安装柜台
- discord.js - 如何让不和谐机器人将您通过 dm 发送给它的图片发送到某个频道
- java - 如何在andorid中使用jsoup发布表单登录?
- android - 为 arm 64 位构建时缺少 DLL“arcore-camera-utility”(适用于 32 位)
- azure - Azure ASR 如何找到要迁移的 On Premise VM 的 IP 地址?
- vba - 获取保存的导入处理的记录数(MS Access、VBA)
- kubernetes - 为什么即使其中一个容器出现错误退出,多个容器的 pod 状态也是 Completed?
- sql - 结构化关系数据库 - 组合相似和相关的表