【发布时间】:2021-05-11 14:30:27
【问题描述】:
我在使用 Angular 8 并将输入参数从父组件绑定到子组件时遇到问题。 我有以下设置:
-app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'parent-child-binding';
showTitle: boolean = true;
childData = [];
onBoolean(){
this.showTitle = !this.showTitle;
}
onComplexAdd(){
this.childData.push("data 4");
this.childData.push("data 5");
}
onComplexEdit(){
this.childData[0] = "data 1 edited";
this.childData[1] = "data 2 edited";
}
onComplexNew(){
this.childData = [
"data 1",
"data 2",
"data 3"
]
}
}
-app.component.html
<button (click)="onBoolean()">Boolean Bind</button>
<button (click)="onComplexNew()">Complex Object New</button>
<button (click)="onComplexEdit">Complex Object Edit</button>
<button (click)="onComplexAdd">Complex Object Add</button>
<app-child [data] = "childData" [showTitle]="showTitle"></app-child>
-child.component.ts
import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {
@Input() showTitle : boolean = true;
@Input() data : Array<any>;
constructor() { }
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
}
ngOnInit(): void {
}
}
-child.component.html
<h3 *ngIf="showTitle">Hello from child</h3>
<p *ngFor="let item of data">{{item}}</p>
所以当我开始时,我会看到以下内容:
和控制台:
当我单击第一个按钮时,正如预期的那样,标题 Hello from child 会显示并消失。
当我点击第二个按钮时,正如预期的那样,我看到了:
和控制台:
当我点击第三个和第四个按钮时,没有任何反应,在 UI 或控制台中没有(onChanges 方法似乎没有触发)。
我做错了什么,或者我想要实现的目标是不可能的?
最好的问候, 朱利安
编辑:在@MBB 和@Apoorva Chikara 发表评论和回答后,我编辑了代码。
<button (click)="onBoolean()">Boolean Bind</button>
<button (click)="onComplexNew()">Complex Object New</button>
<button (click)="onComplexEdit()">Complex Object Edit</button>
<button (click)="onComplexAdd()">Complex Object Add</button>
<app-child [data] = "childData" [showTitle]="showTitle"></app-child>
该版本使按钮可以行动(做某事),但这不是我所期望的。
我的意思是说:
当我点击 UI 中的 Complex Object Edit 按钮时,我看到:
但是在控制台中,没有ngOnChanges回调触发,但是绑定的对象已经改变,我们可以在打印屏幕上看到(<p *ngFor="let item of data">{{item}}</p>)触发并打印出新值。
当我点击Complex Object Add 按钮时也会发生同样的情况。在我看到的 UI 中:
但在控制台中,ngOnChanges 回调未触发,但 UI 包含新添加的数据。
我很困惑,请任何人提供建议?
【问题讨论】:
-
为什么不能换行 (onComplexEdit) -> onComplexEdit() (onComplexAdd) -> onComplexAdd()
-
嗨@MBB 感谢您的评论!我已经编辑了原始问题,因为您建议的更改是有效且适当的,但不能解决我的问题。
标签: javascript html angular typescript