如何在 ng-container 中定义变量?
How to define variable in ng-container?
在我基于 Angular 12 的 Web 应用程序的另一个组件中,我已经在使用 ng-container
和 *ngFor
来遍历数组并显示数组中每个项目的控件像这样:
<ng-container *ngFor="let parameter of parameters">
....
</ng-container>
现在我需要做几乎相同的事情,但不需要迭代任何东西。我只是想有一个定义了变量的容器,然后我可以在容器内使用它。我已经尝试使用 *ngVar
而不是 *ngFor
但后来我得到了这个错误:
Can't bind to 'ngVar' since it isn't a known property of
'ng-container'.
我怎样才能像我已经用 *ngFor
那样做同样的事情,但是对于单个变量而不迭代任何东西?我不想使用 div
,因为我不希望容器元素在呈现后实际存在于我的应用程序的 HTML 中。
我认为对此有一个简单的解决方案,但到目前为止我找不到它。
以下是我希望如何使用此功能:
<ng-container
*ngFor="let parameterColumn of parameterColumns"
matColumnDef="{{ parameterColumn }}"
>
<th mat-header-cell *matHeaderCellDef>
{{ parameterColumn }}
</th>
<td mat-cell *matCellDef="let element">
<ng-container variable="parameter = getParameterById(element, parameterColumn)">
...
</ng-container>
</td>
</ng-container>
我不确定你到底想要什么,但是 ng-template
有你需要的变量功能,你可以将它与 ng-container
一起使用而不插入任何额外的 html,请参考下面的模式,其中使用上下文插入变量。
更新:OP 提供了输入,因此修改了代码,以便变量在 ng-container
中硬编码如下
在下面的示例中,变量是硬编码的,您可以将其插入组件中的任何位置并重复使用硬编码变量。
<ng-container *ngTemplateOutlet="template; context: { variableToBeUsed: 'variable to be used' }"></ng-container>
<ng-template #template let-test="variableToBeUsed">
<h1>variable to be used: {{ test }}</h1>
</ng-template>
控制器
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular 6';
}
在我基于 Angular 12 的 Web 应用程序的另一个组件中,我已经在使用 ng-container
和 *ngFor
来遍历数组并显示数组中每个项目的控件像这样:
<ng-container *ngFor="let parameter of parameters">
....
</ng-container>
现在我需要做几乎相同的事情,但不需要迭代任何东西。我只是想有一个定义了变量的容器,然后我可以在容器内使用它。我已经尝试使用 *ngVar
而不是 *ngFor
但后来我得到了这个错误:
Can't bind to 'ngVar' since it isn't a known property of 'ng-container'.
我怎样才能像我已经用 *ngFor
那样做同样的事情,但是对于单个变量而不迭代任何东西?我不想使用 div
,因为我不希望容器元素在呈现后实际存在于我的应用程序的 HTML 中。
我认为对此有一个简单的解决方案,但到目前为止我找不到它。
以下是我希望如何使用此功能:
<ng-container
*ngFor="let parameterColumn of parameterColumns"
matColumnDef="{{ parameterColumn }}"
>
<th mat-header-cell *matHeaderCellDef>
{{ parameterColumn }}
</th>
<td mat-cell *matCellDef="let element">
<ng-container variable="parameter = getParameterById(element, parameterColumn)">
...
</ng-container>
</td>
</ng-container>
我不确定你到底想要什么,但是 ng-template
有你需要的变量功能,你可以将它与 ng-container
一起使用而不插入任何额外的 html,请参考下面的模式,其中使用上下文插入变量。
更新:OP 提供了输入,因此修改了代码,以便变量在 ng-container
中硬编码如下
在下面的示例中,变量是硬编码的,您可以将其插入组件中的任何位置并重复使用硬编码变量。
<ng-container *ngTemplateOutlet="template; context: { variableToBeUsed: 'variable to be used' }"></ng-container>
<ng-template #template let-test="variableToBeUsed">
<h1>variable to be used: {{ test }}</h1>
</ng-template>
控制器
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular 6';
}