1

我已经看到了很多关于这个问题的问题。但他们对我没有帮助。

这里是我的 HTML

 <div class="pl-lg-4">
          <div *ngIf="isStorySelected; else hi" class="row">
            <div class="col-lg-12">
              <div class="form-group">
                <label class="form-control-label" for="input-username">Story Name</label>
                &nbsp; &nbsp;<label class="form-control-label" for="input-username">Selected option</label>
              </div>
            </div>
          </div>
          <ng-template #hi>
            <div class="row">
              <div class="col-lg-12">
                <div class="form-group">
                  <label class="form-control-label">Select Story</label>
                  <select class="form-control form-control-alternative" value="">
                    <option>some option one</option>
                    <option>some option 2</option>
                  </select>
                </div>
              </div>
            </div>
          </ng-template>

如果我像这样使用 *ngIf 它什么也没有显示。但使用 like ngIf 会显示第一个内容。

这里是我的组件。

import { Component, OnInit } from '@angular/core';
import { Route } from '@angular/compiler/src/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-create-episodes',
  templateUrl: './create-episodes.component.html',
  styleUrls: ['./create-episodes.component.scss']
})
export class CreateEpisodesComponent implements OnInit {

  public activeRoutes: ActivatedRoute;
  public storyId: string;
  public isStorySelected = false;

  constructor(activeRoutes: ActivatedRoute) {
    this.activeRoutes = activeRoutes;

  }

  ngOnInit() {
    this.storyId = this.activeRoutes.snapshot.paramMap.get('id');
    if (this.storyId) {
      console.log('1');
      this.isStorySelected = true;
    } else {
      console.log('2');
      this.isStorySelected = false;
    }
  }
}

在这里我添加了stackblitz url:https ://stackblitz.com/edit/angular-lmxswk?file=src/app/app.component.ts

我已经将 CommonModule 导入了 appModule。

我使用的是最新版本的 Angular。(10)

4

2 回答 2

3

ActivatedRoute的界面

paramMapreturn Observable<ParamMap>,因此您需要将其转换为 observable

name = 'Angular';
public storyId: Observable<boolean>;
public router: ActivatedRoute;

constructor(router: ActivatedRoute) {
  this.router = router;
}

ngOnInit(){
    this.storyId = this.router.paramMap.pipe(
      map((res) =>{
        const currentId = res.get('id');
        if(currentId){
          return  true;
        } else {
          return false;
        }
    }));
  }

内部模板

<div *ngIf="storyId | async; else hi" class="row"></div>

这是工作堆栈闪电战

于 2020-08-17T05:02:15.543 回答
2

希望这能解决您的问题。缺少then选项会导致问题。

<div *ngIf="isStorySelected; then hello; else hi" class="row">
   <ng-template #hello>
      <h1>Hello</h1>
   </ng-template>
   <ng-template #hi>
      <h1>Hi</h1>
   </ng-template>
</div>
于 2020-08-17T04:26:24.037 回答