在我的应用程序中,我有两个组件 - 我们称它们为父级和子级。单击"我正在将数据从父级发送到子级"并显示它。但是在子组件中,我也有能力清除传入数据 - 将传入数据设置为 null。清洁后,我无法再从父级向子级发送和显示数据。这是片段: https://stackblitz.com/edit/angular-ivy-1zdvqj?file=src/app/child/child.component.ts
所以在ChildComponent
中,当您将id
设置为null
.您只更新本地引用。ParentComponent
不知道ChildComponent
在内部将id
的值设置为null
。因此,ChildComponent
需要发出更改并通知ParentComponent
所做的更改。
为了解决这个问题,我们在盒子运算符和@Output
EventEmitter
概念中[()]
香蕉。
在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);
}
当更新的id
从ChildComponent
发出时,它被接收到ParentComponent
,然后ParentComponent
也更新它对null
的引用。
阅读更多:
- 角度 2 向装订:https://angular.io/guide/two-way-binding
- 输入和输出: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>