[英]Angular 4 - How can I get my checkbox to change the value of a variable?
[英]How can I change the value of an Angular template variable?
我想根據條件更改模板變量的值。
<ng-container *ngIf="'first' as myVar">
<ng-container *ngIf="myVar == 'first'">
<ng-container *ngIf="'later' as myVar">
<div>{{myVar}}</div>
</ng-container>
</ng-container>
<div>{{myVar}}</div>
</ng-container>
但是我得到
later
first
代替
later
later
(可能第二個變量與第一個變量不同,只存在於第二個變量的范圍內(這似乎是實現模板變量的一種奇怪方式)。
有沒有一種簡單的方法來更改模板變量的值?
我還想知道是否有辦法將條件( "myVar == 'first'"
)和賦值( "'later' as myVar"
)加入一個表達式而不是兩個嵌套的<ng-container>
。
對於您的主要問題,您的元素只能看到其父母的模板變量。
例如,這將無法編譯:
<ng-container *ngIf="'later' as myVar">
<div>{{myVar}}</div>
</ng-container>
<div>{{myVar}}</div> <!-- No parent TV or reference in component.ts -->
所以你的結論是正確的,因為它是一個不同的值,盡管如果你認為它是生活在那個 DOM-Element 上並不是那么奇怪。 它們更多地意味着對那個特定元素的引用,並且確實對邏輯不太有用。 為此,您最好綁定到您的component.ts文件。
簡而言之,我認為重新分配模板變量是不可能的。 您將只獲得最近父母的價值。
對於你的第二個問題,這有點短(但 /w 相同的結果):
<ng-container *ngIf="'first' as myVar">
<ng-container *ngIf="(myVar == 'first' ? 'later' : '') as myVar">
<div>{{myVar}}</div>
</ng-container>
<div>{{myVar}}</div>
</ng-container>
您還可以(ab)使用ngTemplateOutlet
來實現類似的功能:
<ng-template #s [ngTemplateOutlet]="s" let-a [ngTemplateOutletContext]="{ $implicit: 'first' }">
{{a}}
<ng-template #t [ngTemplateOutlet]="t" let-b [ngTemplateOutletContext]="{ $implicit: a == 'first' ? 'later' : '' }">
{{b}}
</ng-template>
</ng-template>
這是給你的Stackblitz 。
在您的組件中包含用於表示的邏輯實際上是非常好的。 事實上,它幾乎是您的演示組件中應該包含的唯一內容。
最佳實踐是使用Container & Presentation Components的方法。
Angular 允許您在結構指令中設置三元表達式,例如*ngIf="argument === value ? true : false "
這是一個堆棧閃電戰向您展示這一點。 (在鏈接中將 name 的值從 Angular 更改為 React 以查看*ngIf=""
的行為方式)
因此,您不需要像上面的代碼那樣嵌套*ngIf=""
。您還可以在“控制器”-Typescript 文件中執行三元表達式,這樣更清晰,更具可讀性。
如:
public isAngular: boolean = this.name === 'Angular' ? true : false
然后將isAngular
綁定到您的模板*ngIf=""
。
您還可以使用*ngIf="condition; else fallback"
其中fallback
是對另一個內容的模板引用<ng-template #fallback>content goes here</ng-template>
<ng-container *ngIf="myVar === 'first'" else #later>
<div>{{myVar}}</div>
<div>{{myVar}}</div>
</ng-container>
<ng-template #later *ngIf="myVar === 'later'" >
<div>{{myVar}}</div>
<div>{{myVar}}</div>
</ng-template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.