Angular 5动态变量调用求助:无法使用关联数组时的实现方案
Got it, let's figure out how to access those dynamic variables in your Angular template without relying on an associative array. Here are a couple of solid approaches that work perfectly for your scenario:
1. Use a Getter Property in the Component
This is probably the cleanest approach when you need to handle dynamic property names. You can create a getter that builds the property name string and uses JavaScript's bracket notation to fetch the corresponding value:
Component Code:
export class AppComponent { my_a_variable = 'test a'; my_b_variable = 'test b'; type = 'a'; // Value fetched dynamically elsewhere // Getter to return the dynamic variable get dynamicVariable() { // Construct the property name and access it via bracket notation return this[`my_${this.type}_variable`]; } }
Template Usage:
<div>{{ dynamicVariable }}</div>
This keeps your template clean, and the getter will automatically update whenever type changes—Angular's change detection will pick up the update and refresh the value in the template.
2. Conditional Rendering (For Fixed Type Options)
If your type only has a limited set of possible values (like just 'a' and 'b'), you can use conditional logic directly in the template. This is great for readability when the number of options is small.
Option A: Ternary Operator
<div>{{ type === 'a' ? my_a_variable : my_b_variable }}</div>
Option B: ngSwitch (For More Than 2 Options)
If you end up adding more types later, ngSwitch makes the template easier to maintain:
<div [ngSwitch]="type"> <span *ngSwitchCase="'a'">{{ my_a_variable }}</span> <span *ngSwitchCase="'b'">{{ my_b_variable }}</span> <!-- Add a default case for unknown types --> <span *ngSwitchDefault>No matching variable found</span> </div>
Both of these methods avoid associative arrays entirely and play nicely with Angular's template system. Pick the one that fits how many possible type values you expect to handle!
内容的提问来源于stack exchange,提问作者SexyMF

