首页 > 解决方案 > 如何从属性绑定到组件角度获取值

问题描述

我正在使用角度,这是我的问题:

我在名为customers.component.html的父视图中调用一个组件:

<div id="listas" class="listas">
    <div class="fila_lista" *ngFor="let customer of customers">
        <app-details-customer [customer]="customer"></app-details-customer>
    </div>
</div>

如您所见,我正在使用属性绑定将customer变量发送到子组件...

我的问题是,当我收到customer子组件中的变量时,如何获取child.component.ts文件中的值?不在子组件的视图中,只是在child.component.ts

像这样的东西:

export class ChildComponent implements OnInit {
   @Input() customer: any;
   value: any;

   constructor(){
     this.getValue();
   }

    getValue() {
      value = customer.value
   }

有办法做到这一点吗?因为如果我尝试这样做,它不起作用......

谢谢!

标签: htmlangulartypescript

解决方案


据我了解这个问题,您可以使用 setter 函数以及 OnInit 生命周期挂钩函数来实现这一点。

使用二传手:

将您的 @Input() 客户替换为:

@Input() set customer(customerr) {
   this.value = customerr.value;

}
value: any;

使用 onInit:

export class ChildComponent implements OnInit {
   
   @Input() customer: any;
   value: any;
   
   ngOnInit() {
     this.value = this.customer.value;
   }
}

随时再问:)


推荐阅读