【发布时间】:2017-12-28 19:11:42
【问题描述】:
我正在将值从父组件传递给子组件。但在 child.component.html 中显示此值之前,我想在 app.component.ts 文件中将其增加 2 ,然后将其显示在 child.component .html。
在下面的示例中,我在父组件中取一个输入值,在 app.component.ts 中将其增加 2。然后我将它传递给子组件,我想再次将值增加 2。
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() quantity: number;
constructor() {
}
ngOnInit() {
}
childFunction(){
this.quantity = this.quantity + 2;
}
}
child.component.html
<div class="container" style="border: 3px solid #458075; background-color: #6D948C; border-radius: 15px;">
<div class="row">
<div class="col-xs-12">
<p>
Parent value + 4 : {{ quantity }}
</p>
</div>
</div>
</div>
父 html 文件 app.component.html
<div class="container" style="border: 3px solid #515B89; background-color: #79809E; border-radius: 15px;">
<div class="row">
<div class="col-xs-12">
<h1>
{{title}}
</h1>
<label for="box">Value:</label>
<input type="number" class="form-control" [(ngModel)]="value" (ngModelChange)="fun()" />
<p>value: {{ value }}</p>
<p>value + 2 : {{ newvalue }}</p>
</div>
</div>
<div class="row">
<div class="col--xs-12">
<app-child [quantity]=newvalue></app-child>
</div>
</div>
</div>
app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
value: number = null;
newvalue: number = null;
constructor(){
}
ngOnInit(){
}
fun(){
this.newvalue = this.value + 2;
}
}
编辑: 解决方案, 所以我需要使用 ngOnChanges() 但这意味着像这样在子组件中的类上导入它并实现它,
import { Component, OnInit, Input, OnChanges } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {
@Input() quantity: number;
constructor() {
}
ngOnInit() {
}
ngOnChanges(){
this.quantity = this.quantity + 2;
}
}
附加:
仍然有一些奇怪的行为,即子组件中的值 newvalue 在输入任何值之前显示为 2。
好的,我解决了那个特别的小问题,
ngOnChanges(){
if(this.quantity){
this.quantity = this.quantity + 2;
}
}
谢谢,
【问题讨论】:
-
你已经这样做了,有什么问题?
-
除了此处缺少的引号:
[quantity]=newvalue,是什么问题? -
我是?我没有在任何地方调用 childFunction() 。如果数量值发生变化,我会在哪里调用它以便始终更新它?感谢您查看此内容。
-
正确语法:[quantity]="newvalue"
-
考虑在子组件中添加一个
OnChanges生命周期钩子。引号应该围绕“newvalue”(但如果有效,嗯)。
标签: angular data-binding components