1
Guys我是Angular 2的新手,基本上我想使用另一個組件中的一個組件的值,以便能夠根據該值填充數據。使用Typescript調用其他組件在Angular 2中的功能
基本上我有三個組件App.Component,Category.Component和Products.Component。
App.Component是這兩個組件的父項。
這裏是Category.Component代碼
@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);
}
);
}
}
這裏是Products.Component代碼
@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;
}
}
基本上我想從類別組件的getCategoryProducts產品組件,這樣的函數發送產品我可以填充產品。
請幫我 謝謝
您能否請多解釋一下 –
確定使用'#productsComponent',您引用e產品組件。這可能是因爲您在組件上使用局部變量。如果它在DOM元素上(例如'div'),你將得到一個ElementRef實例。使用'#smth =「ngForm」',您將得到應用於具有'exportAs ='ngForm {'的元素的指令。這個局部變量可以通過屬性綁定的輸入傳遞給另一個組件。希望它更清晰;-) –
是的很清楚,謝謝。現在讓我試試這個 –