Angular-重用组件上的数据绑定

时间:2019-07-16 06:58:46

标签: angular

我正在更新模型值,该值需要反映在使用了多次时间(组件可重用性)的html上。

app.component.html

<hello name="{{ name }}"></hello>
<hello name="{{ name }}"></hello>

hello.component.html

<input type="text" [(ngModel)]="name" /> 
<h1>Hello {{name}}!</h1>

enter image description here

场景

  • 所以我已经在Block1 输入文本框中输入了值,相同的值 应该立即反映在Block2 输入文本框上。

注意: 需要简单的代码方法来进行修复。

https://stackblitz.com/edit/angular-f6yzty

2 个答案:

答案 0 :(得分:1)

服务和BehaviorSubject

您可以使用存储输入值和BehaviorSubject的服务。

服务文件:

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

@Injectable()
export class AppService {
  value: BehaviorSubject<string> = new BehaviorSubject('');

  setValue(newValue: string) {
    this.value.next(newValue);
  }
}

hello.component.ts 中:

constructor(private appService: AppService) {  }

  ngOnInit(){
    this.appService.value.subscribe((newValue) => this.uname = newValue);
  }

  update() {
    this.appService.setValue(this.uname);
  }

update()方法应使用hello.component.html中的ngModelChange触发:

<input type="text" [(ngModel)]="uname" (ngModelChange)="update()" />

这是工作中的stackblitz


输出和事件发射器

您还可以使用输出来更新存储在父组件中的全局值。

hello.component.ts 中:

@Input() uname: string;
@Output() unameUpdt: EventEmitter<string> = new EventEmitter<string>();

updated() {
  this.unameUpdt.emit(this.uname);
}

app.component.ts

unameFromParent = '';

updateGlobalValue(value) {
  this.unameFromParent = value;
}

app.component.html

<hello [uname]="unameFromParent" (unameUpdt)="updateGlobalValue($event)"></hello>
<hello [uname]="unameFromParent" (unameUpdt)="updateGlobalValue($event)"></hello>

工作stackblitz

答案 1 :(得分:0)

  

可以在此方法上使用可变对象以进行简单修复。宾语   在父组件中定义的变量,子代可以访问   通过@Input装饰器。

 name = {
    value: 'Angular'
 }

然后可以在两个重复使用的组件中对其进行修改。

stackblitz上的更新修补程序

相关问题