[英]Angular 12 pass data to child in ngFor
我在 PrimeNg TabPanel 中的 ngFor 中將數據傳遞給孩子時遇到問題。 父母是這樣的:
<p-tabPanel header="{{tab.title}}" *ngFor="let tab of tabs; let i = index" [closable]="true" [selected]="active[i+1]">
<app-edit-tab [profile]="profiles[i]" (profileModifiedEvent)="profileModifiedEvent($event, i)"></app-edit-tab>
</p-tabPanel>
子組件是一個編輯選項卡,包含:
@Component({
selector: 'app-edit-tab',
templateUrl: './edit-tab.component.html'
})
export class EditTabComponent implements OnInit {
@Input() profile: Profile;
backupProfile: Profile;
@Output() profileModifiedEvent: new EvenEmitter<Profile>();
ngOnInit() {
this.backupProfile = Object.assign({}, profile);
}
editProfile() {
this.profileModifiedEvent.emit(this.profile);
}
}
我為重置編輯字段制作了備份副本,並在模板中使用輸入配置文件 object 作為 model。 如果我打開 2 個選項卡,我會在 onInit 中檢查備份副本是否正確:第一個選項卡包含傳遞的第一個配置文件的副本,稱為 A,第二個選項卡包含傳遞的第二個配置文件的副本,稱為 B。問題是,在第二個選項卡中,當調用 editProfile() 時,配置文件 object 不是 B,而是 A? 這就像第二個選項卡包含配置文件 A 的內容,但我在 onInit 中檢查了配置文件是 B。有沒有辦法解決這個問題? 每個選項卡都需要一份輸入配置文件 object 的副本。
編輯:也許真正的問題是:從數組中獲取的參數傳遞給子組件的最佳方式是什么?
如果我是你,我會嘗試使用生命周期鈎子ngOnChanges()
。 雖然我不知道您提供的確切用例/問題,但您的子組件有可能在第一次渲染時將 @Input() 值設置為某個值。 然后,當父項中的值發生變化時,它不會在子項中自動更新,因為這就是 Angular 的工作方式。
使用ngOnChanges() {}
檢測變化並相應地更新您的@Input()
值!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.