To model this product linking feature in Angular, I'd use a combination of state management, routing, and component communication:
// 1. Create a service to manage linking state
@Injectable({ providedIn: 'root' })
export class ProductLinkingService {
private sourceProductSubject = new BehaviorSubject<any>(null);
sourceProduct$ = this.sourceProductSubject.asObservable();
setSourceProduct(product: any): void {
this.sourceProductSubject.next(product);
}
linkProducts(sourceId: string, targetId: string): Observable<any> {
// API call to link products
return this.http.post('/api/product-links', { sourceId, targetId });
}
}
// 2. Add link button to product detail component
@Component({
selector: 'app-product-detail',
template: `
<div class="product-details">
<!-- Existing product details -->
<button (click)="findProductToLink()">Link to Another Product</button>
</div>
`
})
export class ProductDetailComponent {
product: any;
constructor(
private router: Router,
private linkingService: ProductLinkingService
) {}
findProductToLink(): void {
this.linkingService.setSourceProduct(this.product);
this.router.navigate(['/search'], {
queryParams: { linking: true, sourceId: this.product.id }
});
}
}
// 3. Modify search component to show linking buttons
@Component({
selector: 'app-search',
template: `
<div *ngIf="isLinkingMode" class="linking-banner">
Select a product to link with {{sourceProduct?.name}}
</div>
<div class="search-results">
<app-product-card
*ngFor="let product of products"
[product]="product"
[showLinkButton]="isLinkingMode && product.id !== sourceId"
(linkClicked)="linkProducts(product.id)">
</app-product-card>
</div>
`
})
export class SearchComponent implements OnInit {
products: any[] = [];
isLinkingMode = false;
sourceId: string;
sourceProduct: any;
constructor(
private route: ActivatedRoute,
private linkingService: ProductLinkingService
) {}
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
this.isLinkingMode = params['linking'] === 'true';
this.sourceId = params['sourceId'];
});
this.linkingService.sourceProduct$.subscribe(product => {
this.sourceProduct = product;
});
}
linkProducts(targetId: string): void {
this.linkingService.linkProducts(this.sourceId, targetId)
.subscribe(() => {
// Show success message or redirect
});
}
}
// 4. Update product card component
@Component({
selector: 'app-product-card',
template: `
<div class="product-card">
<img [src]="product.imageUrl">
<h3>{{product.name}}</h3>
<!-- Normal card content -->
<button *ngIf="showLinkButton"
(click)="onLinkClicked()">
Link to Original Product
</button>
</div>
`
})
export class ProductCardComponent {
@Input() product: any;
@Input() showLinkButton = false;
@Output() linkClicked = new EventEmitter<void>();
onLinkClicked(): void {
this.linkClicked.emit();
}
}
Would you like me to explain or break down the code?