簡體   English   中英

角度6:在ngOnInit中使用@Input的值

[英]Angular 6: use the value of an @Input within an ngOnInit

我想通過使用輸入來檢索模型車的價值,但是我不確定它是如何工作的。 這是我嘗試過的。

@Input() model : Car
car: Car;

    ngOnInit() {
        this.car= this.carService.getcar(model.id);
      }

不幸的模型總是空的,我該怎么辦?

編輯:父HTML

 <app-model
        [model]="car">
  </app-model>

家長ts文件

ngOnInit{
  this.shopService.get()
        .pipe(
          take(1),
          finalize(() => {
                    })
              )
         .subscribe(result => {
              this.car = result;
              });
          })
        )
 }

您必須使用@Input() (帶有方括號)

在另一個組件的HTML中

<app-detail-component [model]="{id: 1, name: 'Carname'}"></app-detail-component>

在您描述的組件的.ts文件中(我假設該組件的名稱為DetailComponent.ts)

@Input() model: Car;
car: Car;

ngOnInit() {
     this.car= this.carService.getcar(model.id);
}

鏈接到官方文檔: https : //angular.io/guide/component-interaction

model為空,因為在子組件中調用ngOnInit之后,在父組件中分配了可變car 您需要在ngOnChanges中而不是ngOnInit調用carService方法。

@Input() model: Car
car: Car;

ngOnChanges() {
  this.car = this.carService.getcar(model.id);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM