不理解在 *ngIf 语句中使用模板变量 [英] Not understanding use of template variables in *ngIf statement

查看:20
本文介绍了不理解在 *ngIf 语句中使用模板变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是最终做出一个设置,让用户可以在查看目录 (spiritwoodart.com) 时更改行数.当我遇到问题时,我什至没有通过摆弄的第一阶段.猜测这是一个根本的误解.无法找到帮助(即我的搜索很糟糕:为什么我不能在 ngif 语句中放置模板变量").如果需要更多信息,请告诉我.感谢您的所有见解,甚至为我的新手火焰.

所以,当我改变时

这个:

 

对此:

或者这个:

 

甚至这个:

 

我收到一个类似这样的错误:

compiler.js:485 未捕获的错误:模板解析错误:没有将exportAs"设置为3"([购物车]="购物车"></product-card>

<div [错误 ->]#n='3' *ngIf="(i+1) % n === 0"class="w-100"></div></ng-容器>"): ng:///AppModule/ProductsComponent.html@12:21

上下文模板:

<div class="col-3"><product-filter [category]="category"></product-filter>

<div class="col"><div 类=行"*ngIf="cart$ | 异步为购物车"><ng-container *ngFor="let p of filteredProducts; let i = index"><div class="col"><product-card [product]="p"[购物车]="购物车"></product-card>

<div *ngIf="(i+1) % 3 === 0"class="w-100"></div></ng-容器>

上下文组件:

import { Cart } from './../models/cart';从'./../cart.service'导入{ CartService };从'./../models/product'导入{产品};从'./../product.service'导入{产品服务};从@angular/core"导入 { Component, OnInit, OnDestroy };从@angular/router"导入{ActivatedRoute};导入 'rxjs/add/operator/switchMap';从rxjs/订阅"导入{订阅};从 'rxjs/Observable' 导入 { Observable };@成分({选择器:应用产品",templateUrl: './products.component.html',styleUrls: ['./products.component.css']})导出类 ProductsComponent 实现 OnInit {产品:产品[] = [];过滤产品:产品[] = [];类别:字符串;//将此字段保留在此类中以对其进行初始化...然后将其委托出去购物车$: Observable<购物车>;构造函数(私人路线:ActivatedRoute,私人产品服务:产品服务,私人购物车服务: CartService) {}异步 ngOnInit() {this.cart$ = 等待 this.cartService.getCart();this.populateProducts();}私人人口产品(){this.productService.得到所有().switchMap(产品=> {this.products = 产品;返回 this.route.queryParamMap;}).订阅(参数=> {this.category = params.get('category');//初始化类别字段this.applyFilter();});}私人申请过滤器(){//设置过滤后的产品数组this.filteredProducts = this.category?this.products.filter(p => p.category === this.category): this.products;}}

解决方案

#模板参考变量.它遵循 DOM 元素,不能那样使用.

ng-init 指令存在于 AngularJS 中并用于此目的,但它在 Angular 中不存在,主要是因为它容易被误用.可以重新创建它,如这个答案所示.

一种解决方法是使用结构指令.truthy 值的典型解决方法是 ngIf 结构指令:

<div *ngIf="(i+1) % n === 0">...

如果值为falsy,则不起作用,因为不会编译嵌套组件.支持虚假值的更通用的解决方法是自定义 ngVar 结构指令,如此处所述.>

my objective is to eventually make a setting where the user can change the number of rows while looking at the catalog (spiritwoodart.com). I didn't even get past the first stage of fiddling when I ran into a problem. Guessing its a fundamental misunderstanding. Having trouble finding help (i.e. my search sucks: "why cant i put a template variables in ngif statement"). Please let me know if more info is needed. Thanks for any and all insights, or even flames for my newbiness.

So, when I change

this:

            <div *ngIf="(i+1) % n === 0"
                class="w-100"></div>

to this:

or this:

            <div #n='3' *ngIf="(i+1) % n === 0"
                class="w-100"></div>

or even this:

            <div *ngIf="(i+1) % {{3}} === 0"
                class="w-100"></div>

I get an error that looks like this:

compiler.js:485 Uncaught Error: Template parse errors:
There is no directive with "exportAs" set to "3" ("
                        [cart]="cart"></product-card>
                </div>
                <div [ERROR ->]#n='3' *ngIf="(i+1) % n === 0"
                    class="w-100"></div>
            </ng-container>
"): ng:///AppModule/ProductsComponent.html@12:21

context-template:

<div class="row">
    <div class="col-3">
        <product-filter [category]="category"></product-filter>
    </div>
    <div class="col">
        <div class="row"
            *ngIf="cart$ | async as cart">
            <ng-container *ngFor="let p of filteredProducts; let i = index">
                <div class="col">
                    <product-card [product]="p"
                        [cart]="cart"></product-card>
                </div>
                <div *ngIf="(i+1) % 3 === 0"
                    class="w-100"></div>
            </ng-container>
        </div>
    </div>
</div>

context-component:

import { Cart } from './../models/cart';
import { CartService } from './../cart.service';
import { Product } from './../models/product';
import { ProductService } from './../product.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/switchMap';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
  products: Product[] = [];
  filteredProducts: Product[] = [];
  category: string; // keep this field in this class in order to initialize it... then delegate it out
  cart$: Observable<Cart>;

  constructor(
    private route: ActivatedRoute,
    private productService: ProductService,
    private cartService: CartService
  ) {}

  async ngOnInit() {
    this.cart$ = await this.cartService.getCart();
    this.populateProducts();
  }

  private populateProducts() {
    this.productService
      .getAll()
      .switchMap(products => {
        this.products = products;
        return this.route.queryParamMap;
      })
      .subscribe(params => {
        this.category = params.get('category'); // initializing category field
        this.applyFilter();
      });
  }

  private applyFilter() {
    // setting the filtered products array
    this.filteredProducts = this.category
      ? this.products.filter(p => p.category === this.category)
      : this.products;
  }
}

解决方案

# is template reference variable. It defers to DOM element and cannot be used like that.

ng-init directive exists in AngularJS and serves this purpose, but it doesn't exist in Angular, primarily because it is prone to be misused. It's possible to recreate it, as shown in this answer.

A workaround is to use a structural directive. A typical workaround for truthy value is ngIf structural directive:

<ng-container *ngIf="3; let n">
  <div *ngIf="(i+1) % n === 0">
    ...

It won't work if the value is falsy, because nested component won't be compiled. More universal workaround that supports falsy values is custom ngVar structural directive, as described here.

这篇关于不理解在 *ngIf 语句中使用模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆