首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的服务流程是Angular11,无法在html中获得1或2的值。

我的服务流程是Angular11,无法在html中获得1或2的值。
EN

Stack Overflow用户
提问于 2022-03-05 06:22:01
回答 2查看 68关注 0票数 1

我的任务:从服务1或2接收到的值,根据值的不同,更改html组件中的样式。使用ng开关指令,我希望将从对象接收的值与指定的模板值进行比较。不应用样式。主要问题是样式没有被应用。

我的组成部分:

代码语言:javascript
复制
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, Self } from '@angular/core';
import { ConfigService, IProductListItem, SliderValueOptions } from 'common-modules';
import { Router } from '@angular/router';
import { debounceTime, filter, takeUntil, tap } from 'rxjs/operators';
import { NgOnDestroy } from '../../core/services/destroy.service';
import { BehaviorSubject } from 'rxjs';
import { OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-product-item',
  templateUrl: './product-item.component.html',
  styleUrls: ['./product-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [NgOnDestroy],
})
export class ProductItemComponent implements OnInit, OnDestroy {
  @Input() product: IProductListItem;
  @Input() doubleClickEnabled: boolean;
  // tslint:disable-next-line:no-output-on-prefix
  @Output() onAddToCart = new EventEmitter<any>();
  themeProperties: number;
  visibility: boolean = false;

  constructor(private _router: Router, private _config: ConfigService, @Self() private onDestroy$: NgOnDestroy) {}

  ngOnInit() {
    this._config.marketplaceConfig.pipe(takeUntil(this.onDestroy$)).subscribe((config) => {
      this.themeProperties = config.structure?.theme;
    });
  }
}

我的html:

代码语言:javascript
复制
<mat-card class="card">
  <div [ngSwitch]="themeProperties">
    <ng-template *ngswitchcase="2">
      {{ themeProperties }}
      <mat-card id="cardbackground">
        <a class="card__link" (click)="redirectToProduct(product)" (dblclick)="doubleClicked(product)">
          <div
            style="display: none"
            class="card__promo"
            *ngIf="product.priceWithDiscount && product?.promoIndividual?.percentDiscount"
          >
            -{{ product?.promoIndividual?.percentDiscount }}%
          </div>
          <!-- <b2b-modern-image mat-card-image [src]="product.photos[0]"></b2b-modern-image> -->
          <img class="mat-card-image" [src]="product.photos" alt="" />
          <mat-card-content class="card__content" [class.has-padding-top]="product && product['discount']">
            <div class="super-sale">супер скидка</div>
            <div *ngIf="product && product['discount']" class="discount">-{{ product['discount'] }}%</div>
            <div
              *ngIf="product && product.promoIndividual && product?.promoIndividual?.percentDiscount"
              class="discount"
            >
              -{{ product?.promoIndividual?.percentDiscount }}
              %
            </div>
            <ng-template #defaultPrice>
              <!--          <span class="price">{{product.price}} ₽</span>-->
            </ng-template>
            <div class="rating">
              <ngx-stars color="#ffd700" [readonly]="true" [initialStars]="product.rating || 0"> </ngx-stars>
              <span class="ml-3">{{ product.views || 0 }} отзывов</span>
            </div>
            <h3 class="name wrap-two-line" [matTooltip]="product?.feed" matTooltipPosition="above">
              {{ product | localize: 'name' }}
            </h3>
            <div class="а">
              <div
                class="d-flex align-items-center"
                *ngIf="product.priceWithDiscount && product.priceWithDiscount != product.price; else defaultPrice"
              >
                <span class="price old">{{ product.price }}₽</span>
              </div>
              <p class="price">{{ (product.priceWithDiscount || 0).toFixed(1) }}₽</p>
            </div>
          </mat-card-content>
        </a>
        <mat-card-footer class="card__footer">
          <a routerLink="/confirm-order" [queryParams]="{ products: product.id }" mat-raised-button color="primary">
            Купить сейчас
          </a>
          <button mat-button color="primary" (click)="addToCart(product)">
            <mat-icon>add_shopping_cart</mat-icon>
          </button>
        </mat-card-footer>
      </mat-card>
    </ng-template>
  </div>
</mat-card>
EN

回答 2

Stack Overflow用户

发布于 2022-03-05 07:29:32

模板开关语句的拼写是区分大小写的,应该是*ngSwitchCase

另外,在这种情况下,ng-template不起作用,您需要使用ng-container

因此,请将语句更改为此布局,并且所有语句都应该工作:

代码语言:javascript
复制
<ng-container *ngSwitchCase="2">

另外,由于您使用的是ChangeDetectionStrategy.OnPush,所以需要手动触发ngSwitch的更改检测。

这是一个工作实例

代码语言:javascript
复制
constructor(private _router: Router, private _config: ConfigService, @Self() private onDestroy$: NgOnDestroy, private cdr: ChangeDetectorRef) {}

  ngOnInit() {
    this._config.marketplaceConfig.pipe(takeUntil(this.onDestroy$)).subscribe((config) => {
      this.themeProperties = config.structure?.theme;
      this.cdr.detectChanges(); // <=== here, after setting the value
    });
  }
票数 0
EN

Stack Overflow用户

发布于 2022-03-05 22:36:55

将构成部分改为:

代码语言:javascript
复制
  themeProperties$: Observable<number>;
  
  ...

  ngOnInit() {
    this.themeProperties$ = this._config.marketplaceConfig.pipe(map((config) => config.structure?.theme))
  }

将模板更改为:

代码语言:javascript
复制
<div [ngSwitch]="themeProperties$ | async">
  <ng-container *ngSwitchCase="2">
     ....
  </ng-container>

问题:

  1. ngSwitchCase指令下的套管错误
  2. OnPush更改检测未正确运行,async管道解析
  3. ng-template不会呈现给DOM。它是其他地方使用的模板。使用ng-container代替。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71359981

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档