angular2 pass ngModel to a child component

前端 未结 3 1435
再見小時候
再見小時候 2020-12-10 12:47

I have ParentComponent and a ChildComponent, and I need to pass the ngModel in ParentComponent to ChildComponent.

// the below is in ParentComponent template         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 13:30

    For Parent -> Child, use @Input

    For Child -> Parent, use @Output

    So to use both:

    In the Parent Component

    Typescript:

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

    Html

    
    
    

    In the Child Component

    Typescript:

    export class ChildComponent {  
       @Input() valueInParentComponent: string;
       @Output() onValueInParentComponentChanged = new EventEmitter();
    } 
    
    onChange(){
      this.onValueInParentComponentChanged.emit(this.valueInParentComponent);
    }
    

    Html

    
    

    Full Example

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

    Other ways to accomplish this:

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

提交回复
热议问题