【问题标题】:Angular 12 - two-way binding gives error: The property and event halves of the two-way binding 'prop_name' are not bound to the same targetAngular 12 - 双向绑定给出错误:双向绑定“prop_name”的属性和事件部分未绑定到同一个目标
【发布时间】:2022-06-20 02:18:35
【问题描述】:

从 Angular 11 迁移到 Angular 12 并弹出此问题:

错误:双向绑定'value'的属性和事件半部没有绑定到同一个目标。”

父页面组件:

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

@Component({
  selector: 'app-parent',
  template: `
    <app-child [(value)]="counterValue"></app-child>
  `,
  styles: []
})
export class ParentComponent {
  counterValue = 0;
}

子组件:

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

@Component({
  selector: 'app-child',
  template: `
    {{ value }}
  `,
  styles: []
})
export class ChildComponent {
  @Input() value = 0;
  @Output() incrementValue = new EventEmitter<number>();

  increase(): void {
    this.value++;
    this.incrementValue.emit(this.value);
  }
}

这里有一个stackblitz 代码供您自己测试:

这是一个错误吗? 还是我错过了什么?

【问题讨论】:

标签: angular typescript angular12 two-way-binding


【解决方案1】:

我只是在这个问题得到解决的同时使用了一种变通方法来继续开发。

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

@Component({
  selector: 'app-parent',
  template: `
    <app-child [value]="counterValue" (incrementValue)="onChange($event)"></app-child>
  `,
  styles: []
})
export class ParentComponent {
  counterValue = 0;
  onChange(n:number) {
    this.counterValue = n;
  }
}

【讨论】:

    【解决方案2】:

    输出装饰器应该是 valueChange 而不是 incrementValue

    根据角度文档进行双向绑定

    inputDecorator @Input propertyName OutputDecorator @Output propertyNameChange

    在我们的代码中,您使用 @Input 作为值,因此 @Output 应该是 valueChange

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 2012-12-17
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      相关资源
      最近更新 更多