簡體   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