2016-12-27 7 views
4

ParentComponent와 ChildComponent가 있고 PgComponent의 ngModel을 ChildComponent에 전달해야합니다.angular2는 자식 구성 요소에 ngModel을 전달합니다.

// the below is in ParentComponent template 
<child-component [(ngModel)]="valueInParentComponent"></child-component> 

어떻게 ChildComponent에서 ngModel의 값을 취득하고 조작 할 수 있습니까?

+0

하고,보다 것은 부모로부터 주입 <아이 컴포넌트 [yourinput]/= "someVariable"> –

답변

8

당신은 자식 클래스에서 ControlValueAccessor를 구현해야합니다. 구성 요소를 각도 값을 사용하여 바인딩 할 수있는 "가치있는"것으로 정의합니다.

여기에 대해 자세히 알아보기 : 당신은 아이 컴퍼넌트 상에 @Input()를 할 수 있습니다 http://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

+1

바로 그게 내가 찾고 있던 건데, 건배 –

+1

어디에서나 보았습니다. 부모님의 onChange 이벤트를 사용하여 강력한 커플 링이 필요한 솔루션을 찾은 것 같습니다. 전체 시간이 있어야한다는 것을 알았습니다. 어떤 것도 필요로하지 않는 구성 요소를 만드는 방법. 내 사자의 마음을 다 지니고 있습니다. –

1

부모 -> 어린이, 어린이의 경우 @Input

를 사용 -> 부모, @Output

을 사용 그래서 모두 사용 : 상위 요소

타이프에서

을 :

onValueInParentComponentChanged(value: string) { 
    this.valueInParentComponent = value; 
    } 

Htm

export class ChildComponent { 
    @Input() valueInParentComponent: string; 
    @Output() onValueInParentComponentChanged = new EventEmitter<boolean>(); 
} 

onChange(){ 
    this.onValueInParentComponentChanged.emit(this.valueInParentComponent); 
} 

HTML을

<input type="text" [(ngModel)]="valueInParentComponent" 
    (ngModelChange)="onChange($event)"/> 

전체 예

: 아이 Component

타이프에서 리터

<child-component 
(onValueInParentComponentChanged)="onValueInParentComponentChanged($event)" 
[valueInParentComponent]="valueInParentComponent"> 
</child-component> 

이러한 목표를 달성하기 위해

https://plnkr.co/edit/mc3Jqo3SDDaTueNBSkJN?p=preview

다른 방법 :

https://angular.io/docs/ts/latest/cookbook/component-communication.html

+0

만약에 ngModel 속성 이름이 변경 되었습니까? 그러면 ChildComponent를 변경해야합니다. 맞습니까? –

+0

업데이트 확인 @ IbraheemAl-Saady –