2017-06-19 28 views
0

我創建了一個顯示用戶信息的user組件。用於顯示和修改的角度 - 重用組件會導致@input問題?

<my-user [person]="person1" (onEdit)="showEdit($event)"></my-user> 

正如你所看到的,我已經發送了通過@Input()顯示的值。

enter image description here

現在我想讓用戶編輯通過另一user組件此信息。

因此,當用戶點擊edit,我發射(通過EventEmitter)的對象到父和在父我有條件地顯示編輯部分(具有相同的值):

這是父成分:

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> Person details : <br> 

    <my-user [person]="person1" (onEdit)="showEdit($event)"></my-user> 

    <ng-template [ngIf]="isEditing" >  <----- conditional edit section 
     Edit Section: 
     <my-user #someElement ></my-user> 
    </ng-template> 

    </div> 
    `, 
}) 

但問題是<my-user>@input,我不傳遞輸入監守它有條件地顯示出來。 因此錯誤:

ERROR TypeError: Cannot read property 'id' of undefined

而且我認爲它試圖利用@input來自內部組件:

ID: <input [(ngModel)]="person.id" type='text' /><br> 

問題

我知道我能/應該創建另一個組件編輯或使用主題訂閱編輯事件 - 但仍然:
我該如何處理盟友顯示相同的組件並填寫(!)需要修改的值?

PLNKR

+0

'@input()人:人= {};'或安全導航運算符'person?.id'? – yurzui

+1

https://plnkr.co/edit/voeHqFHXDvArNN4KKWtw?p=預覽或克隆對象,如果你想保存/取消按鈕https://plnkr.co/edit/XqjKgc4qcGZ7ret1uxjq?p=preview – yurzui

+0

@yurzui謝謝。順便說一句,爲什麼'@ViewChild('someElement')child''是undefined,我明確地在組件中設置了#someElement?我希望通過這個變量填充值 –

回答

2

你爲什麼不創建組件的過程中創建一個Person實例:

export class User { 

    @Input() person:Person = new Person(); 

    constructor() {} 
} 

plnkr

+0

myne愚蠢的錯誤。 –

相關問題