如何将数据从一个组件共享到另一个组件

问题描述 投票:0回答:1

我有两个组件:主页组件和产品列表组件。

这是我的 home.component.ts:

import { Component } from '@angular/core';
import { NgModule } from '@angular/core';
import { Products } from '../products';
import { ProductListComponent } from '../product-list/product-list.component';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [CommonModule, FormsModule, ProductListComponent],
  templateUrl: './home.component.html',
  styleUrl: './home.component.css'
})
export class HomeComponent {
      // products: Products[] = []
      products: Products[]=[
        {
          "productId": 1,
          "productName": "Leaf Rake",
          "productCode": "GDN-0011",
          "releaseDate": "March 19, 2016",
          "price": 19.95,
          "description": "Leaf Rake with 48-inch wooden handle",
          "starRating": 3.2,
          imageUrl: "./assets/images/Leaf-Rake.png"
        },
        {
          "productId": 2,
          "productName": "Garden Cart",
          "productCode": "GDN-0023",
          "releaseDate": "March 18, 2016",
          "price": 32.99,
          "description": "15 gallon capacity rolling garden cart",
          "starRating": 4.2,
          imageUrl: "./assets/images/garden-cart.png"
        },
        { 
          "productId": 5, 
          "productName": "Hammer", 
          "productCode": "TBX-0048", 
          "releaseDate": "May 21, 2016", 
          "description": "Curved claw steel hammer", 
          "price": 8.9, 
          "starRating": 4.8, 
          "imageUrl": "./assets/images/rejon-Hammer.png" 
        }, 
        { 
          "productId": 8, 
          "productName": "Saw", 
          "productCode": "TBX-0022", 
          "releaseDate": "May 15, 2016", 
          "description": "15-inch steel blade hand saw", 
          "price": 11.55, 
          "starRating": 3.7, 
          "imageUrl": "./assets/images/egore911-saw.png" 
        }, 
        { 
          "productId": 10, 
          "productName": "Video Game Controller", 
          "productCode": "GMG-0042", 
          "releaseDate": "October 15, 2015", 
          "description": "Standard two-button video game controller", 
          "price": 35.95, 
          "starRating": 4.6, 
          "imageUrl": "./assets/images/xbox-controller.png" 
        }
      ]
  searching: string = '';//khởi tạo searching kiểu string có giá trị null
  filterProductList: Products[] = []// khởi tạo biến filterProductList

  ngOnInit(): void{
    //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
    //Add 'implements OnInit' to the class.
    this.filterProductList = this.products;
  }
  constructor(){
    this.filterProductList = this.products;   
  }
  filterResults(){
    console.log(this.searching);
    if(!this.searching){
      this.filterProductList = this.products;
    }
      //lọc this.products dựa trên tên sản phẩm
      this.filterProductList = this.products.filter(
      list => list?.productName.toLowerCase().includes(this.searching.toLowerCase())
    )
  }
}

这是我的产品列表.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { Products } from '../products';
import { HomeComponent } from '../home/home.component';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [CommonModule, FormsModule, ProductListComponent],
  templateUrl: './product-list.component.html',
  styleUrl: './product-list.component.css'
})

@Component({
  selector: 'app-product-list',
  standalone: true,
  imports: [HomeComponent, CommonModule],
  templateUrl: './product-list.component.html',
  styleUrl: './product-list.component.css'
})
export class ProductListComponent {
  @Input() productlist: Products[] = [];
}

我正在尝试在 home.component.html 中显示

<app-product-list>
但出现错误:

“'app-product-list' 不是已知元素:

  1. 如果“app-product-list”是 Angular 组件,则验证它是否包含在该组件的“@Component.imports”中。
  2. 如果“app-product-list”是 Web 组件,则将“CUSTOM_ELEMENTS_SCHEMA”添加到该组件的“@Component.schemas”以抑制此消息。ngtsc(-998001)”

这是我的 home.component.html 代码:

<div class="row-mt-3">
    <div class="col-md-6">
        <form class="form-inline">
            <div class="form-group">
                <!-- <label for="searching">Tìm sản phẩm</label> -->
                <input type="text" size="50" [(ngModel)]="searching" 
            (ngModelChange)="filterResults()" name="searching"
            class="input form-control" placeholder="Tìm sản phẩm"/>
            </div>
        </form>
    </div>
</div>
<div class="row mt-3 pl-3 pr-3">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Image</th>
                <th>Product Name</th>
                <th>Code</th>
                <th>Available</th>
                <th>Price</th>
                <th>5 star Rating</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of filterProductList">
                <td scope="row"><img src="{{item.imageUrl}}" width="50px" alt=""></td>
                <td>{{item.productName}}</td>
                <td>{{item.productCode}}</td>
                <td>{{item.releaseDate}}</td>
                <td>{{item.price}}</td>
                <td>{{item.starRating}}</td>
            </tr>
        </tbody>
    </table>
</div>
<app-product-list></app-product-list>

最后,我要对看到这篇文章的人表示感谢。如果我的英文、代码或发帖有什么问题。告诉我一下,非常感谢。

angular angular17
1个回答
0
投票

我认为您的代码中存在一些语法错误。

  1. product-list.component.ts
    中,您添加了两个组件标签。您必须删除选择器值为
    @Component
    app-home
    标签。
  2. 要在
    home.component.html
    中使用产品列表组件,您必须包含如下标签:
    <app-product-list [productlist]="filterProductList"></app-product-list>
  3. 这里我假设您想要将 home 组件的
    filterProductList
    作为产品列表组件的输入传递。您还必须在产品列表和主页组件中实现 Angular 的生命周期挂钩(产品列表中的
    OnInit
    OnChanges
    以及主页组件中的
    OnInit
    )。
© www.soinside.com 2019 - 2024. All rights reserved.