【问题标题】:Angular Conditional Rendering based on Selected Option基于所选选项的角度条件渲染
【发布时间】:2020-08-25 10:38:57
【问题描述】:

我正在关注有关如何创建下拉菜单并让下拉菜单显示一组元素的基本角度教程,但我遇到了如何单独获取每个选项的值的问题。我正在尝试根据下拉列表中的选定选项有条件地呈现标题。我的下拉列表中列出了我的所有三个术语,但始终显示所有三个标题。

术语:

export class Term {
  id: number;
  name: string;
}

打字稿:

import { Term } from './term';
import { Component } from '@angular/core';

@Component({
  selector: 'app-class-search',
  templateUrl: './class-search.component.html',
  styleUrls: ['./class-search.component.css']
})

export class ClassSearchComponent {

  public terms: Term[] = [
    {id: 1, name: 'Summer 2020'},
    {id: 2, name: 'Fall 2020'},
    {id: 3, name: 'Spring 2021'}
  ];

  public selectedTerm: Term = this.terms[0];
  onSelect(termId) {
    this.selectedTerm = null;
    for (var i = 0; i < this.terms.length; i++) {
      if (this.terms[i].id === termId) {
        this.selectedTerm = this.terms[i];
      }
    }
  }
}

HTML:

<div>
  <div class="ui massive menu">
    <select class="ui simple dropdown term" (change)="onSelect($event.target.value)">
      <option value="" selected disabled hidden>Select Term</option>
      <option *ngFor="let term of terms">{{term.name}}</option>
    </select>
  </div>

  <div *ngFor="let term of terms">
    <div *ngIf="this.selectedTerm.id === 1">
      <h1 class="whichterm">{{this.term.name}}</h1>
    </div>

    <div *ngIf="this.selectedTerm.id === 2">
      <h1 class="whichterm">{{this.term.name}}</h1>
    </div>

    <div *ngIf="this.selectedTerm.id === 3">
      <h1 class="whichterm">{{this.term.name}}</h1>
    </div>
  </div>
</div>

【问题讨论】:

  • 这里有很多错误...您应该先尝试遵循 Angular 教程(英雄之旅)。您正在使用旧式 for 循环,没有在选项标记内正确使用 *ngFor,在 HTML 中使用 this(不要!),并在 HTML 末尾使用无用的 *ngFor。 ..
  • 老实说,我只是想要一个简单的示例,说明如何绑定选择中的值以根据所选值显示标题,但我找不到类似的东西。

标签: angular


【解决方案1】:

这是我能想到的最简约的例子:

app.component.html

<h1>{{title}}</h1>
<select (change)='changeName($event)'>
  <option *ngFor='let option of options'>{{option}}</option>
</select>

app.component.ts

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  title = 'not set';
  options = [
    'option 1',
    'option 2',
    'option 3'
  ];
  public changeName( event ) {
    this.title = event.target.value;
  }
}

模板说明:

  • {{title}} 将模型中的 title 属性绑定到您的模板。
  • *ngFor='let option of options' 显示模板中的所有选项。
  • (change)='changeName($event)' 在更改时调用 changeName 函数并为其提供事件对象。

模型解释:

模型非常简单。它有一个 title 属性、一个选项列表和一个修改 title 属性的函数。

StackBlitz:https://stackblitz.com/edit/angular-ivy-x3bcdq

【讨论】:

    猜你喜欢
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2019-02-28
    • 2021-10-26
    • 2018-11-02
    • 2019-07-16
    相关资源
    最近更新 更多