需求如标题所示,下面是详细步骤介绍。
首先,你需要确保你的环境中已经安装了Angular CLI。如果没有,可以通过以下命令安装:
npm install -g @angular/cli
然后你可以创建一个新的Angular项目:
ng new product-app
cd product-app
创建一个名为product
的组件来显示产品列表:
ng generate component product
在 product.component.html
文件中,我们可以添加一个搜索框和一个产品列表:
<input [(ngModel)]="searchText" (input)="search()" placeholder="Search products">
<ul>
<li *ngFor="let product of products" (click)="goToDetail(product.id)">
{{product.name}}
</li>
</ul>
在 product.component.ts
文件中,我们需要定义 searchText
和 products
属性以及 search
和 goToDetail
方法:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent {
searchText = '';
products = [];
constructor(private router: Router) {}
search() {
// TODO: Call API to search products by name
// This is just a mock
this.products = [
{id: 1, name: 'Product 1'},
{id: 2, name: 'Product 2'},
// ...
];
}
goToDetail(productId) {
this.router.navigate(['/product', productId]);
}
}
接下来,我们需要为产品详情页面创建一个组件:
ng generate component product-detail
在 product-detail.component.ts
文件中,我们需要获取路由参数中的产品ID,并调用API来获取产品详情:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
product = null;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
const productId = this.route.snapshot.paramMap.get('id');
// TODO: Call API to get product detail by id
// This is just a mock
this.product = {id: productId, name: 'Product ' + productId};
}
}
在 product-detail.component.html
文件中,我们可以显示产品详情:
<h1>{{product.name}}</h1>
<!-- More product details here -->
最后,我们需要在 app-routing.module.ts
文件中定义路由:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProductComponent } from './product/product.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';
const routes: Routes = [
{ path: 'product', component: ProductComponent },
{ path: 'product/:id', component: ProductDetailComponent },
// Redirect to product list by default
{ path: '', redirectTo: '/product', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
这只是一个非常基础的示例。在实际项目中,你可能需要用到更多的特性,如表单验证,错误处理,状态管理等。
标签:product,name,component,detail,明细,angular,跳转,import,Angular From: https://www.cnblogs.com/sap-jerry/p/17555744.html