我想在我的下拉菜单中进行两种方式的绑定

I want two way binding in the my dropdown menu

我想在我的组件中使用双向绑定。但它不工作。我不明白为什么?

关于详情:

DropdownComponent 单击事件是更改变量 selected。但我想同步更改 AppComponent 变量 select.

这是我的stackblitz

我希望像这样example

my-app 组件需要开始监听 itemChange EventEmiiter。

app.component.html 模板更改为

<h1 >AppComponent selected: {{ select }}</h1>
<p>
    <app-dropdown (itemChange)="select=$event" [data]="['AAA', 'BBB', 'CCC']"></app-dropdown>
</p>

它应该可以工作。

要在 属性 foo 上使用 two way binding,您需要一个名为 fooChanged

的同伴 属性

The [(x)] syntax is easy to demonstrate when the element has a settable property called x and a corresponding event named xChange. Here's a SizerComponent that fits the pattern. It has a size value property and a companion sizeChange event

因此,如果我们以您的示例为例,您需要将下拉组件代码简化为:

import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.css']
})
export class DropdownComponent implements OnInit {
  isOpen = false;
  @Input() selected ;
  @Input() data;
  @Output() selectedChange = new EventEmitter<number>();

  constructor() { }

  ngOnInit() {

  }
  selectItem(item) {
    this.isOpen = false;
    this.selected = item;
    this.selectedChange.emit(this.selected);
  }


}

并像这样使用它:

<app-dropdown [(selected)]="select" [data]="['AAA', 'BBB', 'CCC']"></app-dropdown>

这是一个工作示例https://stackblitz.com/edit/angular-gkxedg

像这样更改您的应用程序组件

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  select = 'i want change select';

  onSelect(text: string) {
    this.select = text;
  }
}

app.component.html

<h1 >AppComponent selected: {{ select }}</h1>
<p>
  <app-dropdown (itemChange)="onSelect($event)" [data]="['AAA', 'BBB', 'CCC']"></app-dropdown>
</p>