我在我的组件中有一个大对象,对象中的属性绑定到模板中的各种组件和输入:
constructor() {
this.data = {
identifier: null,
isRequired: true,
title: 'Untitled',
type: this.fileTypes[0].name,
description: '',
//more code here
}
<app-text-input [(model)]="data.title" label="Title" type="text" variant="white">由于data中的所有属性都与各种输入元素绑定,因此对象中的值保持更新。此组件是另一个组件的子组件。
当父对象上发生某些事件(例如,单击按钮)时,父对象需要能够访问data对象。我该如何实现这一点?我知道有@Ouptuts,但事件发生在父母身上,而不是孩子身上。另外,我现在没有使用任何FormControl类,我需要实现它吗?
发布于 2021-10-25 06:26:57
编辑:这是通过事件发射器的方式,当数据发生变化或发出时,你需要在子组件中订阅它,更新值将显示在子组件或任何其他组件中。
共享服务
SharedService
subject: Subject<Object>;
Parent-Component
constructor(DataService: DataService)
this.DataService.event.next(data);
Child-Component
constructor(DataService: DataService)
this.DataService.event.subscribe((data)=>{
//emitted event with updated data
});每当父组件使用next方法发出时,您都可以接收子组件或其他组件中的数据并对其执行操作。
发布于 2021-10-25 09:12:58
有几种方法可以做到这一点。
1.使用BehaviorSubject。
当使用Reactive Forms而不是ngModel时,这是最好的
子组件:
@Input()
data: BehaviorSubject<T>;
form = new FormGroup({
title: new FormControl()
});
ngOnInit() {
this.form.valueChanges.subscribe(formData => {
this.data.next({
...this.data.value,
...formData
});
});
}<div [formGroup]="form">
<input [formControlName]="title">
</div>父组件:
<child [data]="data"></child>data: BehaviorSubject<T>;
buttonClicked() {
// use this.data.value
}2.使用two-way binding。
这仍然使用ngModel,但需要您自定义表单元素上使用的双向绑定以触发更新:
子组件:
@Input()
data: T;
@Output()
dataChange: EventEmitter<T>;<input [model]="data.title" (modelChange)="data.title = $event; dataChange.next(data)">父组件:
<child [(data)]="data"></child>data: T;
buttonClicked() {
// use this.data
}你也可以混合和匹配它们,例如在ngModel上使用双向数据绑定,如2。,但将BehaviorSubject从父级传递到子级,如1。
https://stackoverflow.com/questions/69703301
复制相似问题