AngulaC语言 重置其值后无法将数据发送到子组件

  • 本文关键字:数据 组件 语言 AngulaC angular
  • 更新时间 :
  • 英文 :


在我的应用程序中,我有两个组件 - 我们称它们为父级和子级。单击"我正在将数据从父级发送到子级"并显示它。但是在子组件中,我也有能力清除传入数据 - 将传入数据设置为 null。清洁后,我无法再从父级向子级发送和显示数据。这是片段: https://stackblitz.com/edit/angular-ivy-1zdvqj?file=src/app/child/child.component.ts

所以在ChildComponent中,当您将id设置为null.您只更新本地引用。ParentComponent不知道ChildComponent在内部将id的值设置为null。因此,ChildComponent需要发出更改并通知ParentComponent所做的更改。

为了解决这个问题,我们在盒子运算符和@OutputEventEmitter概念中[()]香蕉。

ParentComponent.html中,将ChildComponent输入更改为 2 路绑定:

<app-child [(id)]="elementId"></app-child>

ChildComponent中,添加新EventEmitter以通知对输入id所做的任何更改。

@Output() idChange: EventEmitter<number> = new EventEmitter<number>();

然后在reset函数中,发出更新的值;

reset() {
this.id = null;
this.idChange.emit(this.id);
}

当更新的idChildComponent发出时,它被接收到ParentComponent,然后ParentComponent也更新它对null的引用。

阅读更多:

  1. 角度 2 向装订:https://angular.io/guide/two-way-binding
  2. 输入和输出:https://angular.io/guide/inputs-outputs

关键字是 2-Way Binding。你可以在这里阅读它: https://angular.io/guide/two-way-binding

它说

双向绑定的基础知识 双向绑定执行两项操作:

设置特定的元素属性。 侦听元素更改事件。

你错过的是最后一点。

https://stackblitz.com/edit/angular-ivy-98vvnu?file=src%2Fapp%2Fchild%2Fchild.component.ts

在这个分叉的堆栈闪电战中,我在父模板中添加了 (),在子组件中添加了输出。

@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input()
id: number;
@Output()
idChange = new EventEmitter<number>();
constructor() { }
ngOnInit() {
}

reset() {
this.id = null;
this.idChange.emit(this.id);
}
}
<app-child
[(id)]="elementId"
></app-child>

最新更新