在重复使用的组件上进行单向数据绑定

时间:2019-08-01 07:06:52

标签: angular

enter image description here

Block1 Block2 都是相同的组件“ hello.component.ts”(重用组件) 从 Block1 输入框更新的任何数据都应反映在 Block2 输入框上。

但是从 Block2 更新到 Block1 的数据不应更新。

数据应该更新一个方向,没有多方向。

当前在多方向上进行数据更新,对此很难解决。

请给出简短的解决方案。

Stackblitz

1 个答案:

答案 0 :(得分:1)

您看到它是“多向的”,因为您要将相同的对象引用传递给两个组件。

使用简单的字符串替换它,并使用输入/输出,如下所示:

// hello.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
  <input type="text" [ngModel]="name" (ngModelChange)="updateName($event)" />
  <h1>Hello {{name}}!</h1>
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: any;
  @Output() nameChanged: EventEmitter<string> = new EventEmitter();

  updateName(name: string): void {
    this.name = name;
    this.nameChanged.emit(name);
  }
}

// app.component.html
<p> Block1</p>
<hello [name]="name" (nameChanged)="name = $event"></hello>
<p> Block2</p>
<hello [name]="name"></hello>

// 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';
}