我的組件中有大物件,物件中的屬性系結到模板中的各種組件和輸入:
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 類,我是否需要實作它來實作這一點?
uj5u.com熱心網友回復:
編輯:這是通過事件發射器的方式,當資料更改或發射時,您需要在子組件中訂閱它,更新的值將顯示在子組件或任何其他組件中。
事件發射器 Stackblitz
共享服務
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 方法發出時,您都可以在子組件或其他組件中接收資料并對其進行操作。
uj5u.com熱心網友回復:
有幾種方法可以做到這一點。
1. 使用BehaviorSubject.
這在使用反應式表單而不是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.使用雙向系結。
這仍然使用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
}
You could also mix & match these, e.g. use two-way data binding on ngModel as in 2., but pass a BehaviorSubject from parent to child as in 1.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335914.html
上一篇:如何在角管中異步設定變數?
下一篇:如何在Angular中獲取輸入值(element.setAttribute("[(ngModel)]","Title"不起作用)
