0
My friends, I am starting to study angular, I am doing a CRUD of products I came across the following error when creating the component to edit the registered product. I tried a lot of different ways, but nothing worked. The following messages appears:
"error TS2564: Property 'product' has no initializer and is not Definitely Assigned in the constructor. 13 product: Product"
and
"error TS2663: Cannot find name 'product'. Did you Mean the instance Member 'this.product'? 20 this.product = product"
This is my product-update.component.html file and it should show the product that will be edited.
<mat-card>
<mat-card-title>Alterar Produto</mat-card-title>
<form>
<mat-form-field>
<input matInput placeholder="Nome"
[(ngModel)]="product.name" name="name">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Preço (R$)"
[(ngModel)]="product.price" name="price">
</mat-form-field>
</form>
<button mat-raised-button (click)="updateProduct()" color="primary">
Atualizar
</button>
<button mat-raised-button (click)="cancel()">
Cancelar
</button>
</mat-card>
And this is my product-update.component.ts that should be responsible for bringing the information of the selected product. I haven’t finished all the functions of this file yet. Error messages appear on it.
import { ActivatedRoute, Router } from '@angular/router';
import { ProductService } from './../product.service';
import { Component, OnInit } from '@angular/core';
import { Product } from '../product.model';
@Component({
selector: 'app-product-update',
templateUrl: './product-update.component.html',
styleUrls: ['./product-update.component.css']
})
export class ProductUpdateComponent implements OnInit {
product: Product
constructor(private productService: ProductService, private router: Router, private route: ActivatedRoute) { }
ngOnInit(): void {
const id = this.route.snapshot.paramMap.get('id') || ''
this.productService.readById(id).subscribe(prduct => {
this.product = product
});
}
updateProduct():void{
}
cancel(): void{
this.router.navigate(['/products'])
}
}
I need to identify how to fix these two error messages, if any can help, I greatly appreciate.
I think instead of just declaring the product you have to initialize it as an empty product
– Eduardo Vargas
If I do this, it will bring in the empty HTML fields, but I need you to bring the product information related to the ID to edit. or not?
– Henrique Lima
vc can do a ngif="product" in html tbm there at the time of the form
– Eduardo Vargas
There is no missing instantiation Product nay??!
– LeAndrade
You should initialize proudct = new Product(); And the moment you do "readById" you wrote 'prduct' instead of 'product'
– Bruno Cunha
When you create the Product, try to do so:
product!: Product
. I believe that this should solve.– user172788