【问题标题】:Pass value from Child component to Parent component , after child is initialized子组件初始化后,将值从子组件传递给父组件
【发布时间】:2019-08-25 06:22:48
【问题描述】:

现在我在单击发送按钮时将值从子级传递给父级,如何传递相同的数组子级已初始化,我尝试使用“ngAfterViewInit”但没有成功,这里有任何建议。

      child
    @Component({
        selector: 'app-child',
        templateUrl: './child.component.html'
    })
    export class ChildComponent {

        cars = ["Saab", "Volvo", "BMW", "BMW", 'Saab'];

        @Output() msEvent = new EventEmitter();

        constructor() {}

        send() {

            this.msEvent.emit(this.cars);
        }

        // ngAfterViewInit() {

        //   this.msEvent.emit(this.cars);
        // }
    }

    }
        child.component.html : <button (click) = 'send()' class="button">send</button>
    ----------------------------------------

    parent
  @Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  cars:any[];

  constructor() {

  }
  rece($event) {
    this.cars = $event;
  }
}
    app.component.html : <app-child (msEvent) = 'rece($event)' [employees] = 'employees'></app-child>

【问题讨论】:

  • 在 ngAfterViewInit 中对我来说效果很好。当取消注释该代码时,您还有“导出类 ChildComponent 实现 AfterViewInit”?

标签: angular typescript angular-components


【解决方案1】:

ngOnInit() 对于您的情况应该足够了,因为您传递的数据不依赖于“视图”。 在这里查看:StackBlitz example

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 2017-05-01
    • 2018-05-01
    • 2017-05-19
    • 2019-02-17
    • 2020-08-21
    • 1970-01-01
    • 2020-05-27
    • 2019-07-24
    相关资源
    最近更新 更多