在我基于 Angular 12 的 Web 應用程式的另一個組件中,我已經在使用ng-containerwith*ngFor來迭代陣列并為陣列中的每個專案顯示一個控制元件,如下所示:
<ng-container *ngFor="let parameter of parameters">
....
</ng-container>
現在我需要做幾乎同樣的事情,但不需要迭代任何東西。我只是想要一個定義了變數的容器,然后我可以在容器中使用它。我已經嘗試過使用*ngVar而不是*ngFor但我收到了這個錯誤:
無法系結到“ngVar”,因為它不是“ng-container”的已知屬性。
我怎樣才能像我*ngFor對單個變數所做的一樣做同樣的事情,而不需要迭代任何東西?我不想使用a 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>
uj5u.com熱心網友回復:
我不確定您到底想要什么,但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';
}
堆疊閃電戰
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/436731.html
