Switch/Case 更改标题在 Angular 中不起作用

huangapple go评论77阅读模式
英文:

Switch/Case to change Title not working in Angular

问题

appConfig.json

"env": "stage",

app.component.ts

env: string;

constructor(
    private configService: ConfigService
) {}

ngOnInit() {
    this.env = this.configService.config.env;
};

app.component.html

<ng-template [ngSwitch]="env">
    <span *ngSwitchCase="'production'">标题 生产环境</span>
    <span *ngSwitchCase="'stage'">标题 阶段环境</span>
    <span *ngSwitchDefault>默认标题</span>
</ng-template>
英文:

I need to change the title depending on the environment value. But now no titles are displayed.

appConfig.json

&quot;env&quot;: &quot;stage&quot;,

app.component.ts

env: string;

constructor(
    private configService: ConfigService
) {}

ngOnInit() {
    this.environment = this.configService.config.env;
};

app.component.html

&lt;ng-template [ngSwitch]=&quot;env&quot;&gt;
    &lt;span *ngSwitchCase=&quot;&#39;production&#39;&quot;&gt;Title Production&lt;/span&gt;
    &lt;span *ngSwitchCase=&quot;&#39;stage&#39;&quot;&gt;Title Stage&lt;/span&gt;
    &lt;span *ngSwitchDefault&gt;Title Default&lt;/span&gt;
&lt;/ng-template&gt;

答案1

得分: 0

尝试使用ng-container(或div)代替ng-template作为ngSwitch指令的宿主元素。

<ng-container [ngSwitch]="env">
    <span *ngSwitchCase="'production'">标题 生产环境</span>
    <span *ngSwitchCase="'stage'">标题 阶段</span>
    <span *ngSwitchDefault>标题 默认</span>
</ng-container>
英文:

Try using ng-container(or div) instead of ng-template as a host element for ngSwitch directive.

&lt;ng-container [ngSwitch]=&quot;env&quot;&gt;
    &lt;span *ngSwitchCase=&quot;&#39;production&#39;&quot;&gt;Title Production&lt;/span&gt;
    &lt;span *ngSwitchCase=&quot;&#39;stage&#39;&quot;&gt;Title Stage&lt;/span&gt;
    &lt;span *ngSwitchDefault&gt;Title Default&lt;/span&gt;
&lt;/ng-container&gt;

huangapple
  • 本文由 发表于 2023年6月15日 02:47:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定