【问题标题】:Results not displayed with click event (Angular)单击事件未显示结果(Angular)
【发布时间】:2022-01-23 17:22:11
【问题描述】:

我是 Stackoverflow 和 Angular 的新手。我正在用 Angular 编写一个前端应用程序(电子商务)。我将单击事件绑定到 mat-menu 的按钮,以便具有以下行为:单击按钮时,我想显示已单击类别的产品。例如,如果我单击“彩妆”按钮,我希望显示所有类别为“彩妆”的产品。问题是当我点击按钮时,浏览器上什么都没有显示,但我认为应用程序的逻辑是有效的,因为如果我打开浏览器的控制台,就会打印出所选类别的产品。

product.component.html:

<mat-menu #menu="matMenu">
    <button mat-menu-item (click)="categoryFilter('Make-up')"> Make-up</button>
    ... 
</mat-menu>

product.component.ts:

@Component({
    selector: 'app-product',
    templateUrl: './product.component.html',
    styleUrls: ['./product.component.css'] })

export class ProductComponent implements OnInit {
    public products: Product[] = [];
    public product!: Product;

    constructor(private productService: ProductService) { }
    
    ngOnInit() {
        this.getProducts();
    }

    public getProducts(): void{
        this.productService.getProducts().subscribe(
            (response: Product[]) => {
                this.products= response;
            },
            (error: HttpErrorResponse) => {
                alert(error.message);
            }
        );
    }
  
    public categoryFilter(category: string): void{
        this.productService.getProductsByCategory(category).subscribe(
            (response: void) => {
                console.log(response);
            },
            (error. HttpErrorResponse)=>{
                alert(error.message);
            }
        )
    } }

【问题讨论】:

    标签: html angular angular-material frontend mouseclick-event


    【解决方案1】:

    我认为您错过了将响应绑定到属性,然后使用该属性在浏览器上显示数据。

    我不知道响应类型,出于演示目的,假设它是一个字符串

    首先,您需要像创建 public product!: Product; 一样创建一个属性,我们将其命名为 categoryName: string

    在点击事件中,您必须将此属性与您的响应绑定,因此它应该如下所示:

     public categoryFilter(category: string): void{
            this.productService.getProductsByCategory(category).subscribe(
                (response: string) => {
                    this.categoryName = response;
                    console.log(response);
                },
                (error. HttpErrorResponse)=>{
                    alert(error.message);
                }
            )
      }
    

    现在您必须在 HTML 中绑定 categoryName 才能显示它。您可以使用 Angular 的文本插值,它使用大括号 {{}} 在 HTML 中显示字符串值。 因此,您的 HTML 将如下所示:

    <mat-menu #menu="matMenu">
        <button mat-menu-item (click)="categoryFilter('Make-up')"> {{ categoryName }} </button>
        ... 
    </mat-menu>
    

    我建议您继续阅读 Angular 指南。

    Angular 的文本插值:https://angular.io/guide/interpolation

    【讨论】:

    • 谢谢!我按照您的建议解决了问题!就我而言,响应的类型必须是 Product[]。然后唯一要做的就是在 html 代码中添加一个显示获得的产品的表格。
    猜你喜欢
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2022-07-22
    • 2012-04-01
    • 1970-01-01
    相关资源
    最近更新 更多