Angular 2: 结合*ngIf 和#template

Angular 2: combine *ngIf and #template together

<p (mouseover)="info.innerText = 'Detailed info'" 
   (mouseout)="info.innerText = 'Mouseover for details'">
    Select it
</p>
<br>    
<p #info *ngIf="queuedTasks > 0">
    Mouseover for details
</p>

当我尝试合并它时,浏览器调试器说

Error: self.context.info is undefined

可以一起使用吗?

我不确定您能否为此找到解决方案,因为当 *ngIffalse#info 不存在。但是你可以使用一个简单的变量:

在您的 TS 文件中:

export class MyComponent {
    public text = 'Mouseover for details';
    // ...
}

在您的 HTMl 文件中:

<p (mouseover)="text = 'Detailed info'" 
   (mouseout)="text  = 'Mouseover for details'">
    Select it
</p>
<br>    
<p *ngIf="queuedTasks > 0">
    {{text }}
</p>

或者您也可以尝试 [hidden] 而不是 *ngIf

您是否阅读了整个 angular 2 文档,因为我从未听说过 #variable 但听说过 #reference 或 #template ?所以不要犹豫,看看这个 link https://www.concretepage.com/angular-2/angular-2-template-reference-variable-example

Angular2 中的引用必须使用 Viewchild 装饰器声明 在你的情况下:

@ViewChild("info") info: any;
ngAfterViewInit() {
   console.log(this.info); // instead of self.context.info
   // this will give you the ElementRef value for your p element
}

如果您需要在 ngIf 条件中显示内容,请使用 <p>{{info}}</p> 而不是 <p #info>