我有一张表格

<form
  action=""
  class="flex flex-col gap-15 p-10 items-center justify-center border-2 border-black grow-0"
>
  <div name="part1" class="flex flex-col p-10 gap-5 bg-red-100">
    <label for="" class="text-5xl font-bold drop-shadow-md typewriter">
      <h1 class="">Where do we start?</h1>
    </label>
    <select
      [(ngModel)]="flightSelectionService.startingCity"
      name=""
      id=""
      class="min-w-[10rem] rounded-lg text-3xl text-center font-semibold bg-white"
    >
      <option class="border-black bg-white" value="Warsaw">Warsaw</option>
    </select>
  </div>
  @if(flightSelectionService.startingCity !== ''){
  <div name="part2" class="flex flex-col gap-5 bg-blue-100 p-10">
    <label for="" class="text-5xl font-bold drop-shadow-md typewriter">
      <h1>What is a destination?</h1>
    </label>
    <select
      name=""
      id=""
      class="min-w-[10rem] rounded-lg text-3xl text-center font-semibold bg-white"
    >
      <option>Paris</option>
    </select>
  </div>
  }
  <button
    routerLink="/find-a-flight/date"
    class="border-2 border-black rounded-full px-5 py-3 w-fit mx-auto text-lg font-semibold"
  >
    Select the date
  </button>
</form>
<p>selected city is {{ flightSelectionService.startingCity }}</p>

以及一项服务:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class FlightSelectionService {
  startingCity: string = '';
  endingCity: string = '';
  constructor() {}
}

为什么所选城市的价值没有改变:

<p>selected city is {{ flightSelectionService.startingCity }}</p>

当我更改select的值时?ngModel应该提供双向数据绑定,但它不起作用.如何修复它?如果我手动更改服务中的值,它就会显示.

推荐答案

如果您判断浏览器控制台,您将收到以下错误:

错误错误:NG 01352:如果ngModel在表单标签中使用,则 必须设置名称属性或形式 控件必须在ngModel选项中定义为"独立".

Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

请确保您遵循上述错误的说明.您应该为flightSelectionService.startingCity表单控件提供具有值的name属性.

<select
  [(ngModel)]="flightSelectionService.startingCity"
  name="startingCity"
  id=""
  class="min-w-[10rem] rounded-lg text-3xl text-center font-semibold bg-white"
>
  <option class="border-black bg-white" value="Warsaw">Warsaw</option>
</select>

Demo @ StackBlitz

Angular相关问答推荐

添加@ nx/webpack插件 destruct 了Nativescript构建

Angular 单元测试组件s @ Input.'变化值检测

从Observatory的订阅方法外正确接收JSON数据

Angular 升级到v16和Ant设计错误:';nzComponentParams';类型';ModalOptions';中不存在

CDK虚拟滚动由于组件具有注入属性而在滚动时看到错误的值

茉莉花-模板中调用了如何判断角管

如何使用带有17角的Swiper 11.0.5元素

MAT-复选框更改事件未在onSubscriberCheck函数中返回选中的值

如何确保[共享]组件是真正的哑组件?(Angular )

npm install命令在基本Angular 应用程序的天蓝色构建管道中失败

Angular6:RxJS switchMap 运算符未按预期工作

如何在 Angular4 中访问组件的 nativeElement?

无法获得 angular-material md-sidenav 的 100% 高度

Angular 5 Mat-grid 列表响应式

Angular 4:InvalidPipeArgument:管道AsyncPipe的[object Object]

在 Angular rxjs 中,我什么时候应该使用 `pipe` 与 `map`

错误:angular2 中没有 HttpHandler 的提供者

安装特定版本的 ng cli

路由 getCurrentNavigation 始终返回 null

Angular CLI 为已经存在的组件创建 .spec 文件