【问题标题】:add button components dynamically and get values emitted back to parent动态添加按钮组件并将值发送回父级
【发布时间】:2019-01-29 07:36:59
【问题描述】:

我一直无法从父组件动态呈现的子组件获取数据。

Child.component.html:

   <span>Side: {{random_side}}</span>
   <button (click)="submitSide(random_side)">Save</button>

Child.component.ts:

      @Output() eventPassGeneratedSide=new EventEmitter<number>();

      random_side:number=0;

      submitSide(side:number){
       //button clicked. Send data to parent
       this.eventPassGeneratedSide.emit({'side':side});
       }

       onNgInit(){
        this.random_side=Math.floor( Math.random() * 12 );

        }

现在我在父组件中动态创建组件,因为用户可以随意生成任意数量的随机边。

parent.component.html

   <ng-template #generated_side></ng-template>
   <button (click)="generateNewSide()">Generate</button>

parent.component.ts

 @ViewChild('generated_side', {read: ViewContainerRef}) generated_side: ViewContainerRef; //generated child component will go here
  sidesComponent;


 handleSubmittedValue($event){
 //when button in child component is clicked, $event is populated so parent can do something with it.

 //ERROR: THIS NEVER FIRES
console.log($event)
   }


   onNgInit(){

         this.sidesComponent = this.componentFactoryResolver.resolveComponentFactory(childComponent);

}

  generateNewSide(){



    let instance:any=this.generated_side.createComponent(this.sidesComponent);

     instance.instance.eventPassGeneratedSide.subscribe(this.handleSubmittedValue);

  //eventPassGeneratedSide is output variable in Child Component that is supposed to emit avalues to hanldeSubmittedValue
  }

【问题讨论】:

    标签: angular


    【解决方案1】:

    DynamicComponentLoader 不支持输入或输出

    参考这个:https://github.com/angular/angular/issues/6326

    如果您想在孩子和父母之间共享数据,请使用 Subject 或 BehaviourSubject

    创建服务并定义主题的变量类型

    Service.ts

    import { Subject } from 'rxjs';
      eventPassGeneratedSide= new Subject();
    

    Child.ts

    constructor(private service:Service);
     submitSide(side:number){
           //button clicked. Send data to parent
           this.service.eventPassGeneratedSide.next({side:'side'})
    }
    

    Parent.ts

    handleSubmittedValue($event){
    this.service.eventPassGeneratedSide.subscribe(data=>console.log(data))
       }
    

    【讨论】:

    • 谢谢@Chellappan。我对父母有点失落。我们如何调用 hanldeSubmittedValue()。我已经把这条线放在onNgInit中,希望它不断地监听传入的消息或其他东西,但控制台中没有任何输出。简单地说:我如何接收 Child.ts 在我的 Parent.ts 中使用 .next() 方法放置的内容?
    猜你喜欢
    • 2012-07-17
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    相关资源
    最近更新 更多