【问题标题】:Angular 2 - Pass data from parent component to child component on button clicked at parent componentAngular 2 - 在父组件单击的按钮上将数据从父组件传递到子组件
【发布时间】:2018-12-24 20:58:54
【问题描述】:

在 parentComponenet.html

</div><button(click)="discoverClicked()">Discover</button></div>
<child-component></child-component>

在 parentComponent.ts

export class parentComponent implements OnInit {
    discoverClicked(){
       //send data to childComponent
    }
}

在 childComponent.ts

export class childComponent implements OnInit {
    discoverClicked(){
       //received data from parent component
    }
}

有没有办法按照上面的描述做?

【问题讨论】:

  • 子组件是如何渲染的? discoverClicked 很可能会更新父级上的某些属性,您将绑定到父模板中的子组件
  • @ExplosionPills 我已经更新了 parentComponent.html

标签: angular components


【解决方案1】:

在你的父 HTML 标记中添加这个,let-c="close" let-d="dismiss"。 然后在按钮单击时,将“d”作为参数传递。在 ts 文件中,只要你想关闭 NgbModal,就听参数并调用函数 d()

【讨论】:

    【解决方案2】:

    取决于您的数据,一种方法是引入一些变量,例如在父组件中:

    @Component(...)
    export class ParentComponent {
        private data: any;
    
        discoverClicked(){
            // do the thing
            this.data = "some data not matter how you got it";
        }
    }
    

    parent-component.html:

    </div><button(click)="discoverClicked()">Discover</button></div>
    <child-component [data]=data></child-component>
    

    然后在子组件中:

    @Component(...)
    export class ChildComponent {
    
        @Input('data')
        set data(data: any) {
            //do whatever you want with your data here, this data will be passed from parent component
        }
    }
    

    如果您需要更复杂的行为,您可以创建一些服务来为您保存数据,然后将其传递给子组件,例如:

    @Injectable()
    export class DataService {
        private _data: BehaviorSubject<any> = new BehaviorSubject<any>(null);
    
        public setData(data: any){
            this._data.next(data);
        }
    
        public getData(): Observable<any> {
            return this._data.asObservable();
        }
    }
    

    然后在父组件中:

    @Component(...)
    export class ParentComponent {
    
        constructor(private dataService: DataService){}
    
        discoverClicked(){
            // do the thing
            this.dataService.setData("any data that you want");
        }
    }
    

    在子组件中:

    @Component(...)
    export class ChilComponent{
    
        constructor(private dataService: DataService){
            this.dataService.getData().subscribe(data=>{
                // Do whatever you want with your data
            }
        }
    
    }
    

    附: 不要忘记在某处提供服务并取消订阅子组件中的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2016-10-25
      • 2020-04-05
      • 2017-06-25
      • 2017-08-30
      • 2018-04-16
      • 2019-02-27
      相关资源
      最近更新 更多