当原点具有 *ngIf

问题描述 投票:0回答:1
<mat-icon
  #suggestionIcon="cdkOverlayOrigin"
  class="suggestionIcon" 
  *ngIf="part.highlight"
  (click)="openOverlay()"
  cdkOverlayOrigin
>
  add_circle
</mat-icon>
<ng-template 
  #myTemplate
  *ngIf="part.highlight"
  cdkConnectedOverlay 
  [cdkConnectedOverlayOrigin]="suggestionIcon"
> 
 overlay 
</ng-template>

我收到一个错误,说

“InteractionPostComponent”类型上不存在属性“suggestionIcon”。ngtsc(2339) Interaction-post.component.ts(38, 4): 组件InteractionPostComponent模板出现错误。

click on this to see the code

我尝试使用 [style.visible] 代替 if *ngIf,它正在工作,但我想知道为什么 *ngIf 不起作用

angular angular-material2 ng-template angularjs-ng-if
1个回答
0
投票

根据 Template 变量范围文档,当

suggestionIcon
为 true 时,将创建您的
part.highlight
模板引用。范围可以在代码中解释如下:

if (part.highlight) {
  // Create suggestionIcon variable within this scope
}

if (part.highlight) {
  // Access suggestionIcon variable is not possible as it does not exist in global or current scope
}

因此,建议将

<mat-icon>
<ng-template>
元素放置在根
<ng-template>
下,以允许这两个元素可以创建和共享模板引用变量,因为它在范围内。

此外,对于

<ng-template>
,您需要使用
[ngIf]
(模板输入变量语法),而不是
*ngIf
表达式。

<ng-template [ngIf]="part.highlight">
    
  <mat-icon
    #suggestionIcon="cdkOverlayOrigin"
    class="suggestionIcon" 
    (click)="openOverlay()"
    cdkOverlayOrigin
  >
    add_circle
  </mat-icon>
  <ng-template 
    #myTemplate
    cdkConnectedOverlay 
    [cdkConnectedOverlayOrigin]="suggestionIcon"
  > 
    overlay 
  </ng-template>
    
</ng-template>

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.