繁体   English   中英

在 Angular 中的两个组件之间传递值

[英]Passing Values between two components in Angular

我正在尝试将值从一个组件传递到其他组件,到目前为止,我已经引用了一些 tuts 并创建了我的代码,但仍然面临问题。

我的 SelectComponent.ts 中有以下代码

    export class SelectComponent implements OnInit {
 user: LoginUser
 selectLicences = [
  { name: 'Control', id: 1, isChecked: false, quantity: 1 },
  { name: 'Complete', id: 2, isChecked: false, quantity: 1 },
 ]

ControlQuantity=10
CompleteQuantity=20

我想在我的另一个“buyerComponent”中访问 ControlQuantity 和 CompleteQuanitiy

这是 buyerComponent.ts

    export class BuyerComponent implements OnInit, OnDestroy,AfterViewInit {​
@ViewChild('selectProducts', {​ read: SelectComponent, static: false }​)
selectProducts: SelectComponent

CompleteQuantity:number
ControlQuantity:number
ngOnInit() {
    this.CompleteQuantity=this.selectProducts.CompleteQuantity
    this.ControlQuantity=this.selectProducts.ControlQuantitity
}
}

stackblitz 链接: https://stackblitz.com/edit/angular-ivy-umje3g

您有两种选择:

  1. 您可以使用 singleton 服务:
@Injectable({providedIn: 'root'})
export class SharedService {
  sharedValue = 1
}
@Component({…})
export class Component1 implements OnInit {
  public get prop(): number {
    return this.service.sharedValue;
  }
  constructor(private service: SharedService) { }
}
@Component({…})
export class Component2 implements OnInit {
  public get prop(): number {
    return this.service.sharedValue;
  }
  constructor(private service: SharedService) { }
}
  1. 您必须将父组件用作数据桥

父级(桥梁组件)

请注意,父母并没有做很多事情,而是提供了孩子之间共享数据之间的绑定。

<div>
  <app-child1 
    [value]="value"
    (valueUpdated)="onChangeValueFromChildren($event)">
  </app-child1>
  <app-child2 
    [value]="value"
    (valueUpdated)="onChangeValueFromChildren($event)">
  </app-child2>
</div>
@Component({…})
export class ParentComponent implements OnInit {

  value = 2
  
  onChangeValueFromChildren(newValue: number) { 
    this.value = newValue
  }
}

任何子组件

@Component({…})
export class Child1 implements OnInit {

  @Output valueUpdated = new EventEmitter<number>();
  
  onClick() { 
     this.valueUpdated.next(Math.random())
  }
}

可以参考官方文档。 https://angular.io/guide/inputs-outputs#sending-data-to-a-child-component

您可以通过 @Input() 装饰器将数据传递给您的子组件。

export class buyerComponent implements OnInit{
    @Input() CompleteQuantity:number
    @Input() ControlQuantity:number
    
    ngOnInit() {
        this.CompleteQuantity=this.selectProducts.CompleteQuantity
        this.ControlQuantity=this.selectProducts.ControlQuantitity
    }
}

在您的 HTML 页面中,您可以通过子组件的选择器标记传递数据。

更新:看到代码后。

  • 在 AppModule 中,从 Import 中移除 BuyerComponent 和 Products 组件并将它们添加到声明数组中。

  • 在 Buyer.component.html 标签不正确。 正确的标签是“app-products”而不是“app-select-products”。

  • 在产品组件中将这些添加为 @Input() class

     @Input() CompleteQuantity:number @Input() ControlQuantity:number
  • 将现有的 Output() 变量重命名为 products.component.ts 中的另一个名称 class。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM