简体   繁体   中英

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

I'd like to retrieve the value of the model car by using an input, but I'm not sure of how it works. Here's what I've tried.

@Input() model : Car
car: Car;

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

Unfortunetaly model is always empty.How can I do?

EDIT: Parent HTML

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

PARENT ts file

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

您必须使用@Input() (带有方括号)

In HTML of another component

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

In the .ts file of your described component (I assumed the name of the Component is DetailComponent.ts)

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

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

Link to official documentation: https://angular.io/guide/component-interaction

model is empty because variable car in parent component is assigned after ngOnInit is invoked in the child component. You need to call a method of carService in ngOnChanges , not ngOnInit .

@Input() model: Car
car: Car;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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