Hello everyone, I am a newcomer to Angular 2 and I'm looking to utilize the value of one component in another component. This will help me populate data based on that particular value.
In my setup, I have three Components - App.Component, Category.Component, and Products.Component.
Just to clarify, App.Component acts as the parent for both Category.Component and Products.Component.
Let's take a look at the Category.Component Code:
@Component({
selector: 'Categories',
template: `<li *ngFor="#category of categories">
<a class="" href="{{category.Id}}" (click)="getCategoryProducts(category)">{{category.Name}}</a>
</li>`,
providers :[CategoryService]
})
export class CategoriesComponent {
getData: string;
private categories: CategoryModel[] = [];
private products:ProductModel[] = [];
private productsComponent:ProductsComponent;
constructor(private _categoryService : CategoryService){
this._categoryService.getCategories()
.subscribe(
a=>{
this.categories = a;
}
);
console.log(this.getData);
}
getCategoryProducts(category:CategoryModel)
{
this._categoryService.getProducts(category.Id)
.subscribe(
a=>{
this.products = a;
this.productsComponent.populateProducts(this.products);
}
);
}
}
Now, moving on to the Products.Component Code:
@Component({
selector: 'products',
template: `<div class="products-wrapper grid-4 products clearfix loading">
<div *ngFor="#product of products" (click)="getProduct(product)" class="product">
<div class="product-inner" style="background:url({{product.pictureUrl}})">
<div class="time-left">
<span class="text">Hourly Deal</span>
<ul class="countdown clearfix">
<li>
<div class="text">
<span class="hours">00</span>
</div>
</li>
<li>
<div class="text">
<span class="minutes">00</span>
</div>
</li>
<li>
<div class="text">
<span class="seconds">00</span>
</div>
</li>
</ul>
</div>
<span class="discount-tag">{{product.discount}}%</span>
</div>
</div>
</div>`,
providers :[CategoryService]
})
@Injectable()
export class ProductsComponent {
private product:ProductModel;
private products: ProductModel[] = [];
constructor(private _categoryService : CategoryService)
{
this._categoryService.getProducts(0)
.subscribe(
a=>{
this.products = a;
}
);
}
getProduct(product:ProductModel)
{
alert(product.productId);
this.product = product;
}
populateProducts(products: ProductModel[] = [])
{
this.products = products;
}
}
The goal is to transfer Products from the getCategoryProducts function in the Category Component to the Product Component for populating the Products. Any assistance would be greatly appreciated. Thank you!