Angular5:显示ngFor循环中特定元素的编辑表单

时间:2018-02-23 16:14:41

标签: javascript angular angular5

listThirdParty组件使用ngFor循环显示元素列表。 每个元素都有一个'编辑'按钮。用户单击特定元素的按钮并查看编辑表单(因此该特定元素的所有数据都已填充到该表单中)。 EditThirdParty组件显示此编辑表单。

用户点击编辑:变量' thirdPartyToEdit'被分配给所选元素并被发送到EditThirdParty组件。用户可以看到该特定元素的表单。这是预期的行为。 但是,如果用户点击“编辑”#39;在第一个编辑表单仍然打开时,另一个元素上,用户看到两个表单,但选择了要编辑的最新元素用户的数据。我知道这件事正在发生,因为我重新分配了第三部分,以及第三部分。变量与最后选择的项目。 我不了解如何使用正确的数据为每个元素呈现编辑表单。

listThirdParty Component(parent):

@Component({...})
export class ListThirdPartyComponent {
  public showEditForm = false;
  @Input() thirdParties = [];
  public thirdPartyToEdit = {};
  public indexThirdPartyToEdit: number;

  constructor() {}

  private editThirdParty(thirdParty, index) {
    this.thirdPartyToEdit = thirdParty
    this.indexThirdPartyToEdit = index
    this.showEditForm = true;
  }
}

listThirdParty.html

<div class="third-party-block">
   <div *ngFor="let thirdParty of thirdParties, let i = index">   
       <div class="third-party-element">
           <span (click)="editThirdParty(thirdParty, i)" (click)="thirdParty.form = true" (click)="thirdParty.hideme = false">Edit</span>            
           {{thirdParty.name}}
           <div>Role: {{thirdParty.role}}</div> 
           <div>Email: {{thirdParty.email}}</div>
           <div>Phone: {{thirdParty.phone}}</div>
           <div>Ext.: {{thirdParty.ext}}</div>                   
           <edit-third-party 
                 *ngIf="showEditForm" 
                 [hidden]="!thirdParty.form" 
                 [thirdParty]="thirdPartyToEdit> 
           </edit-third-party>
        </div>      
   </div>     
</div>

editThirdParty Component(Child)

@Component({...})
export class EditThirdPartyComponent {
 @Input() thirdParty: any;
 @Output() hideEditThirdParty = new EventEmitter<any>();

 constructor (private requestDist: RequestDistService) {}
    onSubmit(value: any) {
      this.hideEditThirdParty.emit(value)
    }
}

editThirdParty.html

<form #editThirdPartyForm="ngForm" (ngSubmit)="onSubmit(editThirdPartyForm.value)">
   <div class="form-group">
        <input type="text" class="form-control" placeholder="Third Party Name" required [ngModel]='thirdParty.name' name="name">
   </div>   
    ....other form data...            
   <button class="submit" type="submit">Submit</button>     
</form>

0 个答案:

没有答案