【问题标题】:Angular - Changing Input() from child component doesn't notify the parent that it was updated [duplicate]Angular - 从子组件更改 Input() 不会通知父组件它已更新 [重复]
【发布时间】:2020-01-02 13:06:28
【问题描述】:

我有一个父组件,它使用 @Input() 将一些数据 (selectedId) 传递给子组件。

父模板

<child-component [selectedId]="selectedId"></child-component>

子组件使用selectedId如下:

子模板

<select [(ngModel)]="selectedId">
  <option [value]="option.id" *ngFor="let option of options">{{option.name}}</option>
</select>

子组件

export class HelloComponent  {
  @Input()
    set selectedId(id: any) {
      this._selectedId = id;
  }
  get selectedId() {
    return this._selectedId;
  }

  public _selectedId;

  options = [
      {
        "id": "1",
        "name": "Weekly"
      },
      {
        "id": "2",
        "name": "Bi-Weekly"
      },
      {

        "id": "3",
        "name": "Lunar"
      },
      {
        "id": "4",
        "name": "Monthly"
      }
  ]
}

这非常有效。问题是当我直接从子组件更改所选项目时 - 不使用父组件。

当它没有按预期工作时,这是以下情况:

  1. selectedId 由父组件填充(API 调用)
  2. 使用手动更改选择选项(来自child-component
  3. API 被再次调用,它应该设置与在步骤 1 中设置的 ID 相同的 ID。但是这不会触发更改事件。我的假设是父组件不知道在子组件中进行的手动更改,因此它仍然包含对步骤 1 中的 selectedId 的引用,并且不会触发步骤 3 中的更改,因为它是相同的身份证。

我在Stackblitz 上重现了这个问题

我知道我可以使用Output() 和共享服务来解决这个问题,但是我有没有其他方法可以通知家长有关更改检测的信息?

【问题讨论】:

标签: angular angular-changedetection angular-input


【解决方案1】:

当子组件发生变化时,您可以使用@Output 通知父组件


@Component({
  selector: 'hello',
  templateUrl: './hello.component.html',
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input()
    set selectedId(id: any) {
      this._selectedId = id;
      console.log('Child change event --> ', id);
  }
  get selectedId() {
    return this._selectedId;
  }

  @Output() selectedIdChange=new EventEmitter();

  public _selectedId;

  options = [
      {
        "id": "1",
        "name": "Weekly"
      },
      {
        "id": "2",
        "name": "Bi-Weekly"
      },
      {
        "id": "3",
        "name": "Lunar"
      },
      {
        "id": "4",
        "name": "Monthly"
      }
  ]
  onChangeSelectedId(){
    this.selectedIdChange.emit(this.selectedId);
  }
}

并像这样设置值

&lt;hello [(selectedId)]="selectedId"&gt;&lt;/hello&gt;

【讨论】:

    【解决方案2】:

    方法 1:将此变量添加到共享服务并从那里使用它。每当孩子或父母修改它时,它都会更新。

    方法 2:将输入从父组件传递给子组件并添加一个事件发射器,因此每当子组件中的值发生变化时,您应该发出一个事件以更新父组件中的值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 2019-12-12
      • 2016-10-28
      • 2018-07-15
      • 2021-02-10
      • 2021-08-30
      • 1970-01-01
      相关资源
      最近更新 更多